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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
There are a few ways to modify an array while iterating through it:
You can use
array_poporarray_shiftdepending on the order that you want the elements inThis does have a catch in this form, it will end for any falsy value listed in the type comparison table,
array(),false,"",0,"0", andnullvalues will all end thewhileloopTypically this is mitigated with
The strict type comparison should be used as
null == falseand the other falsey values. Again the issue will be that it will stop the iteration if a value in the array is actuallynullA safer way of iterating through an array is to test that it’s not empty:
It’s really that simple
empty()is the opposite of anif()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.