Friday, October 5, 2007

How to use references in foreach safely and sanely in PHP 4

Reference Found: July 30, 2007

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:

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().


- It was in my note, but I don't know where I found them.

No comments: