note 54153 added to control-structures.foreach
| From: | php-general at lists dot php dot net | Date: | Fri, 24 Jun 2005 22:00:07 +0000 |
| Subject: | note 54153 added to control-structures.foreach | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-90926@lists.php.net to get a copy of this message | ||
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.
}
?>
----
Manual Page -- http://www.php.net/manual/en/control-structures.foreach.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+54153
Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+54153&report=yes&reason=added+to+the+manual
Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+54153&report=yes&reason=bad+code
Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+54153&report=yes&reason=spam
Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+54153&report=yes&reason=useless
Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+54153&report=yes&reason=non-english
Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+54153&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+54153&report=yes
Search -- http://master.php.net/manage/user-notes.php