User:DanielRenfro/PHP loops

typical foreach loop
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:

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
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
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
For use with things that implement the traversable interface. PHP's native arrays are not traversable</tt>, but sometimes this is useful when you are working with objects.