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
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.
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With