Home >Backend Development >PHP Tutorial >Why Does Using a Reference in a PHP Foreach Loop Lead to Repeated Element Values?

Why Does Using a Reference in a PHP Foreach Loop Lead to Repeated Element Values?

DDD
DDDOriginal
2024-12-15 07:29:13535browse

Why Does Using a Reference in a PHP Foreach Loop Lead to Repeated Element Values?

Why is the Element Value Repeated in the Array When Using Reference Inside Foreach?

Consider the following PHP code:

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

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

print_r($a);

Surprisingly, the output reveals that the last element's value has overwritten the values of other elements, resulting in:

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

Explaining the Oddity

This behavior is a documented aspect of PHP that stems from the use of a reference (&) in the first foreach loop.

During the first loop, each element of the array is assigned to $v by reference. When $v is modified, it changes the referenced element in the original array. So, when $v is reassigned in the subsequent loop, it inadvertently alters the array element corresponding to the reference.

Solution

To avoid this issue, explicitly unset the reference to the last element before the second foreach loop:

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

print_r($a);

Understanding the Step-by-Step Process

Here's a step-by-step explanation of what happens in the code:

  • First foreach loop:

    • Iteration 1: $v is a reference to $a[0] ('a')
    • Iteration 2: $v is a reference to $a[1] ('b')
    • Iteration 3: $v is a reference to $a[2] ('c')
    • Iteration 4: $v is a reference to $a[3] ('d')
  • At the end of the first loop, $v still references $a[3] ('d').
  • Second foreach loop:

    • Iteration 1: $v remains as a reference to $a[3], but its value is set to $a[0] ('a'). This changes $a[3] to 'a'.
    • Iterations 2-4: Subsequent iterations repeat this process, overwriting $a[3] with the values of $a[1] ('b'), $a[2] ('c'), and finally, $a[3] ('c').

The above is the detailed content of Why Does Using a Reference in a PHP Foreach Loop Lead to Repeated Element Values?. 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