PHP foreach and references
September 26th, 2011
Comments off
The foreach
construct is an usual way to iterate over an array. Since PHP 5, you can also modify the array values using references. Here is one interesting side effect:
<?php $a = range(1,5); foreach($a as &$x) { $x++; } foreach($a as $x) { echo $x; } |
The output is 23455
. This happens because the $x
reference remains even after the foreach
loop ends. The reference is destroyed if you unset $x
after the loop.
This is not very well known. If you have the misfortune to maintain some scripts with a coding style involving little structure, lots of spaghetti code and nested includes than you might be very puzzled by the behavior of a regular foreach loop just because the iterating value was used previously as a reference.