foreach with Reference (Foreach with &)
In PHP, using references in a foreach loop carries implications that users should be aware of. This concept can be seen in the following code snippet:
<br>$a = array('a', 'b', 'c', 'd');</p> <p>foreach ($a as &$v) { }<br>foreach ($a as $v) { }</p> <p>print_r($a);<br>
This code appears straightforward, but its behavior may seem puzzling to some. After executing the first loop, the values in the array $a remain unchanged. However, in the subsequent loop, the last element of $a is unexpectedly overwritten with the values 'a', 'b', and 'c'. This is due to an important behavior in PHP's foreach loops when using references (denoted by the ampersand symbol (&)).
Reference and Modification of Last Element
By using the reference & in the first loop, $v becomes an alias for the current element being traversed in the array. When changes are made to $v, they effectively modify the original element in $a. In this case, the third loop iterates over the array, and even though $v is no longer a reference, it still points to the mutated last element of the array ($a[3]) and overwrites it with the values from previous iterations.
PHP Warning
This peculiar behavior is documented in the PHP manual:
Warning: Reference of a $value and the last array element remain even after the foreach loop. It is recommended to destroy it by unset().
To avoid the unexpected behavior, consider destroying the reference with unset() as shown below:
<br>$a = array('a', 'b', 'c', 'd');</p> <p>foreach ($a as &$v) { }<br>unset($v);<br>foreach ($a as $v) { }</p> <p>print_r($a);<br>
By explicitly unsetting the reference, you ensure that subsequent loops operate on the original values in the array. This approach prevents unintended modification of the array's contents.
The above is the detailed content of Why Does Using References in PHP's `foreach` Loop Unexpectedly Modify the Last Array Element?. For more information, please follow other related articles on the PHP Chinese website!