PHP Pass by Reference in Foreach
In PHP, variables can be either normal variables or reference variables. When assigning a reference of a variable to another variable, the latter becomes a reference variable, essentially binding to the same memory location as the original. This behavior has implications when using the foreach loop with the pass-by-reference syntax (&).
Consider the following code:
$a = ['zero', 'one', 'two', 'three']; foreach ($a as &$v) { } foreach ($a as $v) { echo $v . PHP_EOL; }
The output of this code is:
zero one two two
Why does this occur?
In the first foreach loop, each element of $a is assigned as a reference to the variable $v. This means that any modification to $v also modifies the corresponding element in $a.
Specifically, during the last iteration of the first loop, $v is assigned the value of $a[3] (i.e., 'three'). However, this assignment creates a reference relationship, so $a[3] becomes a reference variable (even though it is not assigned explicitly using &).
In the second foreach loop, the values of the elements in $a are printed. However, since $a[3] is now a reference variable, its value changes along with the value of $v. When $v is assigned the value 'two' during the third iteration, $a[3] also becomes 'two'.
As a result, in the last iteration, $v (which still points to $a[3]) has the value 'two', and 'two' is printed. This explains why 'two' is repeated in the last iteration, instead of printing 'three' as one might intuitively expect.
The above is the detailed content of Why does PHP's foreach with pass-by-reference (&) change array elements unexpectedly?. For more information, please follow other related articles on the PHP Chinese website!