PHP Foreach Pass by Reference: Last Element Duplicating? (Bug?)
Understanding the Issue
Consider the following PHP code:
$arr = array("foo", "bar", "baz"); foreach ($arr as &$item) {} print_r($arr); foreach ($arr as $item) {} print_r($arr); // $arr has changed to ["foo", "bar", "bar"]
After the first loop, the array is printed as expected:
Array ( [0] => foo [1] => bar [2] => baz )
However, after the second loop, the array changes unexpectedly:
Array ( [0] => foo [1] => bar [2] => bar )
Explanation
The issue arises because the first foreach loop passes $item by reference. This means that $item is an alias for the elements in the $arr array. In the first loop, no changes are made to $item or $arr.
However, the second loop passes $item by value. When the value of $item is assigned a new value in the loop, the corresponding element in $arr is also modified.
Specifically, the third element of $arr ("baz") is overwritten with the value of the second element ("bar") during the last iteration of the second loop. This explains why the last element of $arr is duplicated after the second loop.
Is It a Bug?
No, this behavior is not a bug. It is the intended behavior of foreach loops when passing variables by reference. It is important to be aware of this behavior to avoid unexpected changes in your arrays.
Debugging the Output
To help visualize the behavior, the following code adds echo statements to print the value of $item and the array $arr after each iteration of the loops:
echo "<br>"; foreach ($arr as &$item) { echo "Item: $item; Arr: "; print_r($arr); echo "<br>"; } echo "<br>"; foreach ($arr as $item) { echo "Item: $item; Arr: "; print_r($arr); echo "<br>"; }
The output demonstrates how $item and $arr change during the loops, clearly illustrating the behavior described above.
위 내용은 참조에 의한 전달을 사용하는 PHP foreach 루프가 배열을 예기치 않게 변경하는 이유는 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!