After the first loop, foreach $v will be a reference to the last element in $a .
In the next loop, $v will be assigned zero , then one , and then to itself (this is a link). This current value is now one due to a previous assignment. That is why there are two one at the end.
For a better understanding: your code performs the same actions as the following lines:
// first loop $v = &$a[0]; $v = &$a[1]; $v = &$a[2]; // now points to the last element in $a // second loop ($v is a reference. The last element changes on every step of loop!) $v = $a[0]; // since $v is a reference the last element has now the value of the first -> zero $v = $a[1]; // since $v is a reference the last element has now the value of the second last -> one $v = $a[2]; // this just assigns one = one
source share