PHP's Annoying Iterator
PHP has a slightly broken function to help you loop over arrays. It's called next() and you probably think it works like this.
reset( $array );
while( $x = next($array) ) { ... }
That would be typical C or Java iteration. next(), however, increments the counter before returning the value. So, the first call to next() returns the second element in the array!
There's another function, current(), that returns the current value. To use current() and next() to support each other, you write your loop like this:
for( reset($array); $x = current($array); next($array) ) { ... }
Alas, there's a problem here. If the value of current($array) is 0 or not set, then FALSE is returned. This is usually masked by type casting (FALSE+0 = 0) but it's a bug. They say to use each() instead.
To make things even more confusing, the each() function works a lot like next(), except the returns the current value, and then increments the cursor. This is correct iterator behavior, except that each() returns a whole array full of data instead of just the array element.
One way to use each() is:
while( list($key,$val) = each($ar) ) { ... }
The list() pseudofunction causes the = assignment to be done to a list of values. In the above, it's shorthand for: $key = $ar[0] and $val = $ar[1].
What we want is $val, but to get at it, we need to dispose of $ar[0] first. Yuck.
Additionally, pseudofunctions annoy, because they look like functions, but, they aren't. In this case, list() sets up a context where an array on the right side is assigned to a list of variables on the left side.
What we really want is foreach(), but applied like this: foreach( $a as $n ) iterates correctly, assigning the first element to the variable.
Here's a little tool that helps write a for loop for arrays:

