note 53355 deleted from control-structures.foreach by googleguy
| From: | googleguy@php.net | Date: | Wed, 14 Nov 2012 22:34:05 +0000 |
| Subject: | note 53355 deleted from control-structures.foreach by googleguy | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-191983@lists.php.net to get a copy of this message | ||
Note Submitter:
----
How To Use References In Foreach Safely And Sanely In PHP 4.
There are two really really important points to remember about foreach and references:
1. foreach makes a copy
2. references (and unset!) work by directly manipulating the symbol table
In practice, this means that if you have an array of objects (or arrays) and you need to work on
them *in-place* in a foreach loop, you have to do this:
<?php
foreach( $object_list as $id => $the_object ) {
$the_object = & $object_list[$id]; // Re-assign the variable to point to the real object
....
unset($the_object); // Break the link to the object so that foreach doesn't copy the next
one on top of it.
}
?>
This really works. I have used it in dozens of places. Yes, you need it all, including the unset().
You will get extremely hard-to-find bugs if you leave out the unset().
Static.