<?php
$arr = array(0, 1, 2);
foreach ($arr as &$v) {
$v += 1;
}
foreach ($arr as $v) {
var_dump($v);
}
/*
Output:
int(1)
int(2)
int(2)
Lines 2-4 iterate over $arr by reference. So, when we reach line 5, $v is still
a reference to last element of the array (e.g. $v = &$arr[2]). There are only
2 possible ways to "unlink" $v from the array element:
- use unset(): unset($v);
- make $v a reference to another value: $v = &$x;
Since $v is reference to last element of the array, the foreach loop in
lines 5-7 will execute like this:
1) $v = $arr[0]; $arr is now [1, 2, 1], since writing to $v updates $arr[2]
2) $v = $arr[1]; $arr is now [1, 2, 2], since writing to $v updates $arr[2]
3) $v = $arr[2]; This causes self-assignment (e.g. $arr[2] = $arr[2]), which
doesn't change the value of $arr.
*/