Reputation: 3804
$array = array('1','3','20','10');
foreach ($array as $i=>$arr) {
if ($i==0) unset($array[$i]);
}
Question: would removing one element mess up the order of the iteration of this loop? What happen when I remove the element with the index smaller/equal/bigger than the current iterating index?
What should I avoid to do when modifying the original array while iterating over it?
Edit: In case the array is passed by reference?
Upvotes: 0
Views: 169
Reputation: 10080
Particularly to your provided code, once
$array = array('1','3','20','10');
is declared, the keys are bound, so
if($i==0) unset($array[$i]);
will only unset '1'
, and you will be left with
array(2) {
[1]=>
string(1) "2"
[2]=>
string(1) "3"
}
And as @cleong said, PHP seems to create a copy of the array when iterating:
$arr=array("1","2","3");
foreach($arr as $idx=>$val)
{
if(isset($arr[1])) unset($arr[1]);
echo $val."\n";
}
var_dump($arr);
will return
1
2
3
array(2) {
[0]=>
string(1) "1"
[2]=>
string(1) "3"
}
So it's "OK" to unset elements inside an iteration, as long as the unset
would not generate error (e.g. unsetting an already unset variable).
But, I don't think this is a good idea. If your question is "how to avoid this", provide an example of why you have to do this.
Upvotes: 1
Reputation: 7626
PHP creates a copy of the array when you use a foreach loop(). Even if you blow away the array entirely, the iteration will continue as through nothing has happened. To wit:
$array = array("a", "b", "c");
foreach($array as $element) {
$array = null;
echo "$element ";
}
Output:
a b c
Upvotes: 0