Home >Backend Development >PHP Tutorial >Why Does PHP's Foreach Loop with References Overwrite the Last Array Element?

Why Does PHP's Foreach Loop with References Overwrite the Last Array Element?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-27 14:37:14335browse

Why Does PHP's Foreach Loop with References Overwrite the Last Array Element?

Unexpected Behavior of Foreach Loop Using References

When using PHP's foreach loop with references, strange behavior can occur as demonstrated by the following code snippet:

$a = array('a', 'b', 'c', 'd');

foreach ($a as &$v) { }
foreach ($a as $v) { }

print_r($a);

This code is intended to iterate through the array $a using a reference variable $v in the first loop and a non-reference variable $v in the second loop. However, surprisingly, the output shows that the last element of the array, 'd', has been overwritten:

Array
(
    [0] => a
    [1] => b
    [2] => c
    [3] => c
)

Explanation of the Behavior

This unexpected behavior is well-documented in PHP's documentation. It warns that when using references in a foreach loop, the reference of the last element of the array remains even after the loop has ended. To avoid this issue, it is recommended to unset the reference variable using unset().

In our example, the reference variable $v remains a reference to the last element of $a after the first loop. When the second loop iterates over $a, each iteration of the loop reassigns the value to $v. However, since $v is a reference to the last element of $a, it overwrites the value of that element.

Step-by-Step Guide to the Behavior

To further clarify, here is a step-by-step guide to what happens in our code snippet:

  1. The first foreach loop assigns references of each array element to $v.
  2. In the second foreach loop, $v still refers to the last element of $a, 'd'.
  3. The loop iterates through $a, re-assigning each value to $v.
  4. Since $v is a reference to the last element of $a, it overwrites the value of that element with each iteration.
  5. The last element of $a ends up being overwritten with the value of the previous element.

Solution

To avoid this issue, simply unset the reference variable $v after the first loop:

foreach ($a as &$v) { }
unset($v);
foreach ($a as $v) { }

The above is the detailed content of Why Does PHP's Foreach Loop with References Overwrite the Last Array Element?. 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