note 75742 added to control-structures.foreach

From: Date: Wed, 13 Jun 2007 23:09:31 +0000
Subject: note 75742 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-127463@lists.php.net to get a copy of this message
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? ---- Server IP: 69.147.83.197 Probable Submitter: 71.170.123.57 ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- https://master.php.net/note/edit/75742 Del: integrated -- https://master.php.net/note/delete/75742/integrated Del: useless -- https://master.php.net/note/delete/75742/useless Del: bad code -- https://master.php.net/note/delete/75742/bad+code Del: spam -- https://master.php.net/note/delete/75742/spam Del: non-english -- https://master.php.net/note/delete/75742/non-english Del: in docs -- https://master.php.net/note/delete/75742/in+docs Del: other reasons-- https://master.php.net/note/delete/75742 Reject -- https://master.php.net/note/reject/75742 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#127463) next »