User:DanielRenfro/PHP loops

typical foreach loop edit

foreach ( $array as $key => $value ) {
   // ...
}

Supposedly holds the array in a cache and iterates over it. This is supported by the fact that you cannot change things within the array whilst inside the foreach loop without using the reference operator (&) like so:

foreach ( $array as &$key => &$value ) {
   // now you can mess with $key and $value and have it actually change them 
}

This method is inappropriate for iterating over arrays of objects (if you intend to throw those objects away at the end of each loop interation.) This is due to the cache -- it keeps an internal reference to the object, so that when you try and throw it away (by using unset() or $o->__descruct()), PHP won't remove it from memory or free up that space in memory. I emphasize 'inappropriate' because I've yet to see any proof of this behavior, but this is what I read.

typical for loop edit

for ( $i=0, $c=count($array); $i<$c; $i++ ) {
   // ...
}

This method is quite useful for iterating over most anything non-associative. The last part of the loop-expression increments $i, meaning that it must be numeric.

while loop edit

reset( $array );
while ( list($key, $value) = each($array) ) {
   // ...
}

This method is good for iterating over any type of array, but it uses a few more function calls per iteration (one to list() and one to each().)

  • This is the preferred method for iterating over arrays of objects that are being unset.

while / traversable edit

$a->rewind();
while ( $a->valid() ) {
   $key = $a->key();
   $value = $a->current();
   // ...
   $a->next();
}

For use with things that implement the traversable interface. PHP's native array()s are not traversable, but sometimes this is useful when you are working with objects.