note 85773 deleted from control-structures.foreach by googleguy
| From: | googleguy@php.net | Date: | Wed, 14 Nov 2012 22:30:09 +0000 |
| Subject: | note 85773 deleted from control-structures.foreach by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-191969@lists.php.net to get a copy of this message | ||
Note Submitter: rhi
----
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("...");
?>