This question already has an answer here:
- Strange behavior Of foreach 2 answers
I have this code:
$a = array ('zero','one','two', 'three');
foreach ($a as &$v) {
}
foreach ($a as $v) {
echo $v.PHP_EOL;
}
Can somebody explain why the output is: zero one two two .
From zend certification study guide.
I found this example also tricky. Why that in the 2nd loop at the last iteration nothing happens ($v stays 'two'), is that $v points to $a[3] (and vice versa), so it cannot assign value to itself, so it keeps the previous assigned value :)
I think this code show the procedure more clear.
Result: (Take attention on the last two array)
First loop
Yes! Current
$v
=$a[3]
position.Second loop
because
$a[3]
is assigned by before processing.This question has a lot of explanations provided, but no clear examples of how to solve the problem that this behavior causes. In most cases, you'll probably want the following code in your pass by reference
foreach
.This :
is the same as
OR
OR
Because on the second loop,
$v
is still a reference to the last array item, so it's overwritten each time.You can see it like that:
As you can see, the last array item takes the current loop value: 'zero', 'one', 'two', and then it's just 'two'... : )