Reference Variable in PHP Foreach
In the given code, the issue arises due to the use of reference variables in the first foreach loop. Here's an explanation:
$a = ['zero', 'one', 'two', 'three']; foreach ($a as &$v) { // $v is a reference to the current array element } foreach ($a as $v) { echo $v . PHP_EOL; }
In PHP, variables can be normal or reference variables. Normal variables hold the value of the data, while reference variables point to the location of the data.
In the first loop, we have $v = &$a[0]; hence, $v becomes a reference to the first element of the array, 'zero'. This means any modifications to $v will be reflected in $a[0], and vice versa.
Now, in the second loop, we have $v = 'two'. Since $v is a reference variable, this operation also modifies the corresponding element in the array, $a[3].
Lastly, in the second foreach loop, when we iterate over each element, we see the output:
This demonstrates the impact of using reference variables in a foreach loop, leading to the repetition of the last value updated in the first loop.
The above is the detailed content of What Happens When Using Reference Variables in a PHP Foreach Loop?. For more information, please follow other related articles on the PHP Chinese website!