Deletion of element on a string not working, after conversion to an array

Viewed 67

The code below explains how to delete an element by using the unset function, I have used a string and converted the string into an array, Now trying to delete the first and last element. But the elements do not get deleted. Help would be grateful

<?php
$string="Cupid";  //orginal string
$stringmod= str_split($string);  //converted the string to an array
$length= count($stringmod); //length of the string
for($i=0; $i<$length; $i++) 
{

    if($i == 0 || $i == $length-1) //condition to be executed
    {
        
        unset($stringmod[$i]); //delete elements
    
    }
    
}
print_r($stringmod);
?>
2 Answers

array_shift will remove the first element from an array, re-indexing numerical keys.

array_pop will remove the last.

$string="Cupid";  //orginal string
$stringmod= str_split($string); 

array_shift($stringmod);
array_pop($stringmod);

print_r($stringmod);

If you want to do it via a loop, as per @jibsteroos comment, you are pretty much there, you just need to correctly reference the test counter in the for loop.

About your code, you are missing $ before length in the loop.

Despite that: there is no need to loop through the array - you can directly address the elements. The following will work:

<?php
   $string="Cupid";
   $stringmod= str_split($string);
   unset($stringmod[count($stringmod)-1]);
   unset($stringmod[0]);
   print_r($stringmod);
?>

The functions array_pop and array_shift will do the same (remove last/first element from your array). They are better if you want to do it again later in the code (the PHP is using associative arrays, so $stringmod[0] is the first element only in the beginning - when you remove it, there is no longer $stringmod[0], so executing unset($stringmod[0]) twice will not remove two "first" elements, but only one). So probably the best answer in this case is:

<?php
   $string="Cupid";
   $stringmod= str_split($string);
   array_pop($stringmod);
   array_shift($stringmod);
   print_r($stringmod);
?>

P.S. Based on the comment from Andrew below my answer, you can also do reordering with array_values() function or remove elements with array_splice() (which will also reorder). Personally I do not like to use them because they take resources and when possible I do not rely on that the arrays are with sorted indexes of magic numbers :)

Related