Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP array_Shift() stops suddenly

I got this simple example to illustrate what issue am having.

Suppose you have:

$myArray =  array("A","B","C","D","E","F","I","G","H");

The goal is to remove first elements of this Array in a loop.

Let's say:

for($i=0; $i<count($myArray ); $i++){

    var_dump($myArray );

//...Remove the first Element of this array while $i is less than it's length.

    array_shift($myArray); 
}

This Removes the first element in the first loop and two or three more, suddenly, it gives up removing the first Elements.

As per the Documentation:

array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be touched. And the it suggests this example.

   <?php 
         $stack = array("orange", "banana", "apple", "raspberry"); 
         $fruit = array_shift($stack); 
print_r($stack); 
?>

The Out put: Array ( [0] => banana [1] => apple [2] => raspberry )

The Example clearly shows what I want. But, why doesn't it continue removing to the Last element?

If this is how it was designed to be. Then is there anyway in to achieve the Removal/Deletion of first Array Element to the Last Element... Until count($myArray) returns 0 (Zero).??

Any Suggestion is Highly appreciated.

like image 681
ErickBest Avatar asked Jun 11 '26 09:06

ErickBest


1 Answers

Simply:

while (count($myArray) > 0) {
    array_shift($myArray); 
}

See Demo

like image 135
Mark Miller Avatar answered Jun 12 '26 23:06

Mark Miller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!