note 46348 added to control-structures.foreach

From: Date: Thu, 07 Oct 2004 19:21:37 +0000
Subject: note 46348 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-78150@lists.php.net to get a copy of this message
(PHP 5.0.2) Pay attention if using the same variable for $value in both referenced and unreferenced loops. $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(). ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+46348 Delete -- http://master.php.net/manage/user-notes.php?action=delete+46348&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+46348&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#78150) next »