3v4l.org

run code in 300+ PHP versions simultaneously
<?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. */
Output for 7.1.0 - 7.1.33, 7.2.0 - 7.2.34, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.31, 8.2.0 - 8.2.26, 8.3.0 - 8.3.14, 8.4.1 - 8.4.2
int(1) int(2) int(2)

preferences:
77.51 ms | 407 KiB | 5 Q