note 54153 deleted from control-structures.foreach by danbrown
| From: | danbrown@php.net | Date: | Tue, 28 Apr 2009 13:09:40 +0000 |
| Subject: | note 54153 deleted from control-structures.foreach by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-153920@lists.php.net to get a copy of this message | ||
Note Submitter:
----
The poster who submitted this loop style for iterating over variables by reference:
<?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.
}
?>
Using foreach() means you end up making a copy of the value, and then quickly reassign it to be a
reference. This is a waste of the original copy operation.
You may want to consider this, more meaningful and readable alternative:
<?php
reset($object_list);
while (list($key) = each($object_list)) {
$the_object = & $object_list[$key]; // 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.
}
?>