note 75742 rejected from control-structures.foreach by philip
| From: | philip@php.net | Date: | Wed, 18 Jun 2008 00:12:23 +0000 |
| Subject: | note 75742 rejected from control-structures.foreach by philip | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-140548@lists.php.net to get a copy of this message | ||
Note Submitter: kirk at proofed dot net
----
Foreach by reference bug:
Can anyone explain this one to me? I've had similar problems with the way foreach handles
values by reference. This is the simplest example I could come up with:
<?php
$array1 = array('a' => 1);
$array2 = array('b' => 2);
$array3 = array('c' => 3);
$matrix = array($array1, $array2, $array3);
foreach($matrix as &$array)
$array['d'] = 4;
foreach($matrix as $array)
print_r($array);
?>
This should just add the key / value pair ['d'] = 4 to each array.
The expected output is then:
Array ( [a] => 1 [d] => 4 ) Array ( [b] => 2 [d] => 4 ) Array ( [c] => 3 [d] => 4
)
The actual output is:
Array ( [a] => 1 [d] => 4 ) Array ( [b] => 2 [d] => 4 ) Array ( [b] => 2 [d] => 4
)
My guess:
The first foreach loop disrupts the pointer making the second foreach loop point to the last element
twice.
Is anyone able to explain this better or create an even simpler example where this happens?