PHP 5.3 Anonymous functions as iterators
In my recent experimentation of the new 5.3 anyonymous functions, I’ve come up with a custom iterator as a proof of concept:
function anonyIterator($array,$want_array = FALSE){
$acount = count($array);
$itcount = 0;
return function() use ($acount,&$itcount,$array,$want_array) {
$member = $itcount >= $acount
? FALSE
: $array[$itcount];
$itcount++;
if ($member) {
return $want_array === FALSE
? $member
: array($itcount,$member);
}
else {
return $member; // end of array
}
};
}
anonyIterator( array $array, boolean $want_array )
Example usage:
$array = array('cat','dog','frog','bird','zebra','lion');
$iterator = anonyIterator($array,TRUE);
while(list($i,$animal) = $iterator()) {
echo "$i => $animal\n";
}
$iterator = anonyIterator($array);
while($animal = $iterator()) {
echo "ANIMAL: $animal\n";
}
So, we have another use of anyonymous function in php. However, this is very impractical and I don’t see any use since for this as long as we have the ArrayIterator class.

Leave a Reply