note 85773 added to control-structures.foreach
| From: | rhi at osu1 dot php dot net | Date: | Wed, 17 Sep 2008 10:22:01 +0000 |
| Subject: | note 85773 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-144470@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:
$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("...");
----
Server IP: 212.124.37.9
Probable Submitter: 85.127.212.165
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- https://master.php.net/note/edit/85773
Del: integrated -- https://master.php.net/note/delete/85773/integrated
Del: useless -- https://master.php.net/note/delete/85773/useless
Del: bad code -- https://master.php.net/note/delete/85773/bad+code
Del: spam -- https://master.php.net/note/delete/85773/spam
Del: non-english -- https://master.php.net/note/delete/85773/non-english
Del: in docs -- https://master.php.net/note/delete/85773/in+docs
Del: other reasons-- https://master.php.net/note/delete/85773
Reject -- https://master.php.net/note/reject/85773
Search -- https://master.php.net/manage/user-notes.php