How to use Generators in PHP

Support for generators (via the yield keyword) has been added to PHP 5.5 and allows you to create simple iterators without the use of the Iterator interface. What’s this all mean? It boils down to overhead, generators use less memory than an implementation of the Iterator interface or simply creating an array that would contain the values.

Before looking at a generator, let’s take a look at a bit of code to generate an array with even numbers between 0 and 1 million:

$values = range(0, 1000000, 2

foreach ($values as $value)
{
	echo $value . "n"
}

Easy enough, right? Sure, but the peak memory usage (on my Mid 2012 Macbook Air) was about 70MB. Now let’s implement the same functionality using a generator function:

function evens($min, $max)
{
	for ($i = $min $i <= $max $i += 2)
	{
		yield $i
	}
}

foreach (evens(1, 1000000) as $value)
{
	echo $value . "n"
}

Was the bit more coding worth it? You better believe it! On the same system, the generator code used less than a quarter of a megabyte! Worth noting is that even though the generator used significantly less memory, it did perform slower at around 2.5 seconds compared to the 1.9 seconds without the generator. Like most things, YMMV and it’s always worth weighing the pros and cons when making your coding decisions.

Josh Sherman - The Man, The Myth, The Avatar

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.


If you found this article helpful, please consider buying me a coffee.