Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterate over array in php but add to / remove from array during iteration

Tags:

arrays

php

In PHP, How do I do this:

$test = array(1,2,3,4);

$i=0;
While (!empty($test)) {

  //do something with $test[i];

  //remove  $test[$i]; 
  unset($test[$i]);

}

Thanks

like image 618
jbd Avatar asked Sep 01 '11 03:09

jbd


2 Answers

There are a few ways to modify an array while iterating through it:

You can use array_pop or array_shift depending on the order that you want the elements in

while( $val = array_pop( $arr ) )
-or-
while( $val = array_shift( $arr ) )

This does have a catch in this form, it will end for any falsy value listed in the type comparison table, array(), false, "", 0, "0", and null values will all end the while loop

Typically this is mitigated with

while( ( $val = array_pop( $arr ) ) !== null )

The strict type comparison should be used as null == false and the other falsey values. Again the issue will be that it will stop the iteration if a value in the array is actually null

A safer way of iterating through an array is to test that it's not empty:

while( $arr )
//while( count( $arr ) )
//while( !empty( $arr ) )
{
  $val = array_pop( $arr );

  //for forward iteration
  //$val = array_shift( $arr );
}

It's really that simple empty() is the opposite of an if() check. There is a hidden advantage to !empty() in the while loop, which is that it suppresses errors if the variable is undefined at the time of the check.

In well-written code™ this isn't an issue, however well-written code™ doesn't occur naturally in the wild, so you should be extra careful just-in-case.

like image 124
zzzzBov Avatar answered Sep 27 '22 21:09

zzzzBov


Perhaps you mean:

$test = array(1,2,3,4);

while (!empty($test)) {
  //do something with $test[0];

  //remove $test[0]; 
  unset($test[0]);
}

which will effectively pop the head of the array until it's empty.

It might make more sense to use array_pop, which pulls the last element from the array:

while(!empty($test)){
    $value = array_pop($test);
    // do work with $value
}

...or array_shift which will pull from the front of the array:

while(!empty($test)){
    $value = array_shift($test);
    // do work with $value
}
like image 35
Mark Elliot Avatar answered Sep 27 '22 20:09

Mark Elliot