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.25 - 7.1.32, 7.2.0 - 7.2.33, 7.3.0 - 7.3.33, 7.4.0 - 7.4.33, 8.0.0 - 8.0.30, 8.1.0 - 8.1.28, 8.2.0 - 8.2.18, 8.3.0 - 8.3.4, 8.3.6
int(1) int(2) int(2)
Output for 8.3.5
Warning: PHP Startup: Unable to load dynamic library 'sodium.so' (tried: /usr/lib/php/8.3.5/modules/sodium.so (libsodium.so.23: cannot open shared object file: No such file or directory), /usr/lib/php/8.3.5/modules/sodium.so.so (/usr/lib/php/8.3.5/modules/sodium.so.so: cannot open shared object file: No such file or directory)) in Unknown on line 0 int(1) int(2) int(2)

preferences:
156.17 ms | 402 KiB | 177 Q