A few years ago, after being bewildered by infinite loop problems and convoluted paging algorithms, I wondered why the PHP community hadn’t adopted iterator based looping and sunset the three-statement for-loop like Python.

Some of the resistance I encountered were arguments regarding memory efficency & performance using the range() function. These were the days where PHP lacked generators and yield statements.

In Python’s image, I built xrange(). I wrote an article, Killing The For Loop, about it in PHP|Architect magazine (when still in print) and published my extension into the PECL respository.

In combination with PHP’s SPL, you can do some quite amazing things. For those that don’t know, SPL is the PHP “equivalent” of C++’s Standard Template Library. It offers generic algorithmic data structures, iterators and such. Following is a contrived example, using one of my own package supplied filters.

<?php
// vim: set ts=4 sw=4 noet:
assert(extension_loaded('xrange'));

// display all odd numbers 1 .. 20
print_r(array_values(
iterator_to_array(
new OddFilterIterator(xrange(1, 20))
)
));

The real power comes from chaining, slicing, appending and filtering iterators together. Creating large batch sets of numbers together without any memory overhead.

Last I heard, it’s still a standard package in the SUSE Linux repositories. You can still use it, include the source I published in the article, or adopt the modern generator syntax… which does not work with SPL natively in this way.

Anyone want to take this over??