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中文網其他相關文章!