Home >Backend Development >PHP Tutorial >Why does the last element in a PHP array duplicate when using a foreach loop with pass-by-reference?

Why does the last element in a PHP array duplicate when using a foreach loop with pass-by-reference?

Susan Sarandon
Susan SarandonOriginal
2024-11-14 20:19:01458browse

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:

  • $item references the value at $arr[0], which is 'foo'.
  • $item and $arr[0] both point to 'foo'.
  • This process repeats for $arr[1] and $arr[2].

At the end of the first loop, $item still points to $arr[2].

In the second loop:

  • $item is assigned the value of $arr[0], which is 'foo'.
  • $arr[2] (still referenced by $item) is also set to 'foo'.
  • This overwrites the original value of 'baz' at $arr[2].
  • The same process occurs for $arr[1], and finally, $arr[2] is assigned the value of $arr[2], which is now 'bar' due to the previous iteration.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn