note 46348 deleted from control-structures.foreach by googleguy

From: Date: Wed, 14 Nov 2012 22:34:42 +0000
Subject: note 46348 deleted from control-structures.foreach by googleguy
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-191986@lists.php.net to get a copy of this message
Note Submitter: gardan at gmx dot de ---- (PHP 5.0.2) Pay attention if using the same variable for $value in both referenced and unreferenced loops. <?php $arr = array(1 => array(1, 2), 2 => array(1, 2), 3 => array(1, 2)); foreach($arr as &$value) { } foreach(array(1,2,3,4,5) as $value) { } echo $test[3]; ?> What happens here is that after the first foreach() loop, you have in $value a reference to the last element of $arr (here: array(1, 2)). Upon entering the second foreach(), php assigns the value. Now value is assigned to where $value (which is still a reference) points, that is, the last element of $arr. Your output will be "5", not the expected "Array". To be on the safe side, unset($value) before entering the next foreach().

« previous php.notes (#191986) next »