note 39995 added to control-structures.foreach

From: Date: Wed, 18 Feb 2004 03:50:02 +0000
Subject: note 39995 added to control-structures.foreach
Groups: php.notes 
Request: Send a blank email to php-notes+get-65333@lists.php.net to get a copy of this message
There is a really really big pitfall to watch out for if you are using "foreach" and references. Recall this example: <? $a = "Hello"; $b =& $a; // $b now refers to "Hello" $b = "Goodbye"; // BOTH $a and $b now refer to "Goodbye" ?> This also applies to the loop variable in a foreach construct. This can be a problem if the loop variable has already been defined as a reference to something else. For example: <? // Create some objects and store them in an array $my_objects = array(); for($a = 0; $a < $num_objects; $a++) { $obj =& new MyObject(); $obj->doSomething(); $my_objects[] =& $obj; } // later on in the same function... foreach($my_objects as $obj) { // Note that we are trying to re-use $obj as the loop variable $obj->doSomethingElse(); } ?> When the "for" loop exits, $obj is a reference to the last MyObject that was created, which is also the last element in the "my_objects" array. On every iteration, the foreach loop will do the equivalent of: <? $obj = $my_objects[$internal_counter++]; ?> $obj will now refer to the appropriate element in the array. But recall the reference example at the top. Because $obj was already defined as a reference, any assignment to $obj will overwrite what $obj was referring to. So in other words, on every foreach loop iteration, the last element in the array will be overwritten with the current array element. To avoid this problem, either use a differently named loop variable, or call "unset()" on the loop variable before you begin the foreach(). It would be more intuitive PHP unset() the loop variable before a foreach began, maybe they'll put that in a later version. ---- Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+39995 Delete -- http://master.php.net/manage/user-notes.php?action=delete+39995&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+39995&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#65333) next »