Reference Behavior in 'foreach' Loop: Understanding Array Modifications
In PHP, employing references within a 'foreach' loop can lead to unexpected array modifications. This behavior is highlighted in the following code:
$a = array('a', 'b', 'c', 'd'); foreach ($a as &$v) { } foreach ($a as $v) { } print_r($a);
The output this code produces is unexpected:
Array ( [0] => a [1] => b [2] => c [3] => c )
Step-by-Step Explanation
To understand this behavior, it's essential to follow the changes that occur during each iteration of the 'foreach' loop:
Upon completion of the first 'foreach' loop (reference iterations), $v still holds a reference to $a[3] ('d').
Thus, after the second 'foreach' loop (value iterations), the array $a has been modified with 'c' appearing twice.
Resolving the Issue
To avoid this unexpected behavior, it is recommended to unset the reference after each iteration:
$a = array('a', 'b', 'c', 'd'); foreach ($a as &$v) { } unset($v); foreach ($a as $v) { } print_r($a);
This will yield the expected output:
Array ( [0] => a [1] => b [2] => c [3] => d )
The above is the detailed content of Why Does Using References in PHP's `foreach` Loop Lead to Unexpected Array Modifications?. For more information, please follow other related articles on the PHP Chinese website!