PHP Foreach Pass by Reference and Array Modification
In PHP, using pass by reference in a foreach loop can lead to unexpected behavior. Consider the following code:
$arr = ["foo", "bar", "baz"]; foreach ($arr as &$item) {} // Array remains unchanged: ["foo", "bar", "baz"] foreach ($arr as $item) {} // Array is modified: ["foo", "bar", "bar"]
Why does the second loop modify the array?
In the first loop, the $item variable is passed by reference. This means that changes made to $item also affect the corresponding element in the $arr array. However, in the second loop, $item is passed by value. Thus, changes made to $item do not affect the array.
Crucially, after the first loop, $item still references the last element of $arr. When the second loop iterates over the array, each value of $item overwrites the last element of $arr because they both refer to the same memory location.
Debugging the Output
To understand the behavior, we can echo the current value of $item and recursively print the $arr array during each loop iteration.
First Loop:
foo Array ( [0] => foo [1] => bar [2] => baz ) bar Array ( [0] => foo [1] => bar [2] => baz ) baz Array ( [0] => foo [1] => bar [2] => baz )
After the first loop, $item points to the last element of $arr.
Second Loop:
foo Array ( [0] => foo [1] => bar [2] => foo ) bar Array ( [0] => foo [1] => bar [2] => bar ) bar Array ( [0] => foo [1] => bar [2] => bar )
As each value of $item is overwritten, it also modifies the last element of $arr.
Is it a Bug?
No, this behavior is not a bug but rather the intended behavior of pass-by-reference. It's important to understand the implications of passing variables by reference and to use it appropriately.
The above is the detailed content of Why does using pass-by-reference in a PHP `foreach` loop modify the array after the loop ends?. For more information, please follow other related articles on the PHP Chinese website!