Home > Article > Backend Development > Why does the last element in a PHP array duplicate when using a foreach loop with pass-by-reference?
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.
The above is the detailed content of Why does the last element in a PHP array duplicate when using a foreach loop with pass-by-reference?. For more information, please follow other related articles on the PHP Chinese website!