Home >Backend Development >PHP Tutorial >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:
Second foreach loop:
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!