PHP Foreach Pass by Reference: Last Element Duplication Mystery Unveiled
Consider the following PHP code:
$arr = ["foo", "bar", "baz"]; foreach ($arr as &$item) { /* do nothing by reference */ } print_r($arr); foreach ($arr as $item) { /* do nothing by value */ } print_r($arr);
Upon execution, it unexpectedly modifies the original array $arr, resulting in the following output:
Array ( [0] => foo [1] => bar [2] => baz ) Array ( [0] => foo [1] => bar [2] => bar )
Understanding the Behavior
After the initial foreach loop, the variable $item remains a reference to the same memory location as $arr[2]. Consequently, each iteration of the second foreach loop, which passes arguments by value, replaces the referenced value (and hence $arr[2]) with the new iteration's value.
Detailed Explanation
In the first loop:
At the end of the first loop, $item still points to $arr[2].
In the second loop:
Clarifying Misconception
This behavior is not considered a bug. It aligns with the intended behavior of references in PHP. Similar results would be observed if you used the following syntax outside of a loop:
for ($i = 0; $i < count($arr); $i++) { $item = $arr[$i]; }
Conclusion
When working with references in PHP, it is crucial to recognize that modifications made through the referenced variable will also affect the original value. This behavior can be leveraged effectively or avoided depending on the desired outcome.
위 내용은 참조별 전달과 함께 foreach 루프를 사용할 때 PHP 배열의 마지막 요소가 중복되는 이유는 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!