note 85773 modified in control-structures.foreach by danbrown

From: Date: Mon, 20 Apr 2009 15:30:13 +0000
Subject: note 85773 modified in control-structures.foreach by danbrown
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-153517@lists.php.net to get a copy of this message
If you use foreach with references, don't forget to unset the reference if you are not sure that a later piece of code doesn't use the same variable name. Example: <?php $latest_tutorials = $db->queryAll("select * from tutorials"...); foreach ($latest_tutorials as &$tut) $tut["comments"] = $db->queryOne("select count(*) ..."); // ... $tut = $db->queryRow("..."); print_tutorials($latest_tutorials); print_tutorial($tut); ?> Here the last entry of latest_tutorials will be replaced by the row that is fetched by the $tut = $db->queryRow("..."); line because $tut is still referencing the last array entry. Solution: <?php foreach ($latest_tutorials as &$tut) $tut["comments"] = $db->queryOne("select count(*) ..."); unset($tut); // ... $tut = $db->queryRow("..."); ?> --was-- If you use foreach with references, don't forget to unset the reference if you are not sure that a later piece of code doesn't use the same variable name. Example: $latest_tutorials = $db->queryAll("select * from tutorials"...); foreach ($latest_tutorials as &$tut) $tut["comments"] = $db->queryOne("select count(*) ..."); // ... $tut = $db->queryRow("..."); print_tutorials($latest_tutorials); print_tutorial($tut); Here the last entry of latest_tutorials will be replaced by the row that is fetched by the $tut = $db->queryRow("..."); line because $tut is still referencing the last array entry. Solution: foreach ($latest_tutorials as &$tut) $tut["comments"] = $db->queryOne("select count(*) ..."); unset($tut); // ... $tut = $db->queryRow("..."); http://php.net/manual/en/control-structures.foreach.php

« previous php.notes (#153517) next »