PHP Generators
What Is a Generator? In simple terms: A generator is a function that produces values one at a time , only when they are needed, instead of building a complete array first. It pauses after handing out
What Is a Generator?
In simple terms: A generator is a function that produces values one at a time, only when they are needed, instead of building a complete array first. It pauses after handing out each value and continues from the same point when the next value is requested.
Technically: Any function containing the yield keyword is a generator function. Calling it does not run its body; it returns a Generator object, which implements the Iterator interface. Each time the caller asks for the next value (for example, in a foreach loop), the function runs until the next yield, hands out that value, and suspends — keeping all its local variables — until it is resumed.
Why Generators Are Useful
| Benefit | Example |
|---|---|
| Low memory use | Process a 5 GB log file line by line instead of loading it into an array |
| Lazy evaluation | Values are computed only if they are actually used |
| Infinite sequences | IDs, Fibonacci numbers, or date series with no fixed end |
| Simple iterators | Much less code than writing a class that implements Iterator |
| Pipelines | Chain filtering and transformation steps without intermediate arrays |
Basic Syntax
<?php
function numbers(): Generator
{
echo "[start]\n";
yield 1;
echo "[after 1]\n";
yield 2;
echo "[end]\n";
}
$generator = numbers();
echo "Generator created\n";
foreach ($generator as $number) {
echo "Got $number\n";
}
Output
Generator created
[start]
Got 1
[after 1]
Got 2
[end]
How It Works
- Calling
numbers()returns aGeneratorobject — no code in the function runs yet, which is why "Generator created" appears before "[start]". - The
foreachloop asks for the first value. The function runs untilyield 1, hands out1, and pauses. - The loop body prints "Got 1", then asks for the next value. The function resumes after
yield 1, prints "[after 1]", and pauses atyield 2. - When the function reaches its end, the generator is finished and the loop stops.
The output interleaves the function's code and the loop body, which shows that the two take turns.
Generators vs Arrays: Memory
<?php
function rangeArray(int $max): array
{
$result = [];
for ($i = 1; $i <= $max; $i++) {
$result[] = $i;
}
return $result;
}
function rangeGenerator(int $max): Generator
{
for ($i = 1; $i <= $max; $i++) {
yield $i;
}
}
$start = memory_get_usage();
$sum = 0;
foreach (rangeArray(1_000_000) as $n) { $sum += $n; }
echo "Array: " . round((memory_get_peak_usage() - $start) / 1024 / 1024, 1) . " MB peak\n";
memory_reset_peak_usage(); // PHP 8.2+
$start = memory_get_usage();
$sum = 0;
foreach (rangeGenerator(1_000_000) as $n) { $sum += $n; }
echo "Generator: " . round((memory_get_peak_usage() - $start) / 1024 / 1024, 1) . " MB peak\n";
Output (exact values depend on the PHP version and platform)
Array: 16 MB peak
Generator: 0 MB peak
The array version stores one million integers at once. The generator holds only the current value, so its memory use stays constant no matter how many values it produces.
Yielding Keys
yield $key => $value produces key–value pairs, just like iterating over an associative array:
<?php
function countries(): Generator
{
yield 'IN' => 'India';
yield 'JP' => 'Japan';
yield 'BR' => 'Brazil';
}
foreach (countries() as $code => $name) {
echo "$code: $name\n";
}
Output
IN: India
JP: Japan
BR: Brazil
Without an explicit key, generators use automatic integer keys starting at 0.
Infinite Sequences
A generator can run forever, because values are produced only on demand. The consumer decides when to stop:
<?php
function fibonacci(): Generator
{
[$a, $b] = [0, 1];
while (true) {
yield $a;
[$a, $b] = [$b, $a + $b];
}
}
function take(iterable $items, int $count): Generator
{
if ($count <= 0) {
return;
}
foreach ($items as $key => $item) {
yield $key => $item;
if (--$count === 0) {
return;
}
}
}
echo implode(' ', iterator_to_array(take(fibonacci(), 10), false)) . "\n";
Output
0 1 1 2 3 5 8 13 21 34
take() stops after ten values, so the infinite while (true) loop inside fibonacci() is never a problem: once nobody asks for more values, the generator simply stays paused and is cleaned up.
Lazy Pipelines
Small generator functions can be chained into a processing pipeline, where each value flows through all steps before the next value is produced:
<?php
function mapItems(iterable $items, callable $fn): Generator
{
foreach ($items as $key => $item) {
yield $key => $fn($item);
}
}
function filterItems(iterable $items, callable $predicate): Generator
{
foreach ($items as $key => $item) {
if ($predicate($item)) {
yield $key => $item;
}
}
}
$numbers = (function (): Generator {
for ($n = 1; ; $n++) {
yield $n;
}
})();
$oddSquares = mapItems(filterItems($numbers, fn(int $n): bool => $n % 2 === 1), fn(int $n): int => $n * $n);
echo implode(', ', iterator_to_array(take($oddSquares, 4), false)) . "\n";
Output
1, 9, 25, 49
The source is an infinite sequence of numbers, yet the pipeline finishes after computing exactly four results — only seven numbers are ever generated. With arrays, each step would build a complete intermediate array, which is impossible for infinite input and wasteful for large input. (take() is the function from the previous example.)
Delegation: yield from
yield from passes through all values of another generator (or array or iterator):
<?php
function inner(): Generator
{
yield 1;
yield 2;
return 3;
}
function outer(): Generator
{
$result = yield from inner();
yield $result;
}
foreach (outer() as $value) {
echo $value . ' ';
}
echo "\n";
Output
1 2 3
yield from inner()yields1and2to the caller ofouter().- A generator can
returna final value.yield fromevaluates to that value, here3, whichouter()then yields itself. - For a generator used directly, the return value is available with
$generator->getReturn()after it has finished.
Key Collisions With iterator_to_array()
<?php
function letters(): Generator
{
yield 'a';
yield 'b';
}
function moreLetters(): Generator
{
yield from letters();
yield 'c';
}
print_r(iterator_to_array(moreLetters()));
print_r(iterator_to_array(moreLetters(), false));
Output
Array
(
[0] => c
[1] => b
)
Array
(
[0] => a
[1] => b
[2] => c
)
yield from keeps the inner generator's keys (0, 1), and the outer generator's own automatic keys also start at 0, so 'c' gets key 0 and overwrites 'a'. Passing false as the second argument ignores the keys and returns a proper list. Use it whenever keys do not matter.
Generators Run Only Once
A generator cannot be restarted after it has advanced:
<?php
function three(): Generator
{
yield 1;
yield 2;
yield 3;
}
$generator = three();
foreach ($generator as $n) {
echo $n;
}
echo "\n";
try {
foreach ($generator as $n) {
echo $n;
}
} catch (Exception $e) {
echo get_class($e) . ": " . $e->getMessage() . "\n";
}
Output
123
Exception: Cannot traverse an already closed generator
To iterate again, call the generator function again to create a new generator. If you need the values several times, convert them once with iterator_to_array() (if they fit in memory).
Sending Values Into a Generator
yield is also an expression: $value = yield; receives a value passed in with $generator->send($value). This makes two-way communication possible:
<?php
function collector(): Generator
{
$items = [];
while (true) {
$item = yield;
if ($item === null) {
return $items;
}
$items[] = strtoupper($item);
}
}
$collector = collector();
$collector->send('php');
$collector->send('mysql');
$collector->send(null);
print_r($collector->getReturn());
Output
Array
(
[0] => PHP
[1] => MYSQL
)
The first send() starts the generator, runs it to the first yield, and delivers 'php' as the result of that yield. Sending null ends the loop and returns the collected items. This technique is the foundation of coroutines, but in everyday code, generators are mostly used for iteration; for concurrency, PHP 8.1 introduced Fibers (see PHP Fibers).
Practical Example: Aggregating a Large CSV File Lazily
<?php
$file = __DIR__ . '/sales.csv';
file_put_contents($file, "region,amount\nNorth,120\nSouth,200\nNorth,80\nWest,50\nSouth,100\n");
function csvRows(string $path): Generator
{
$handle = fopen($path, 'r');
if ($handle === false) {
throw new RuntimeException("Cannot open $path");
}
try {
$header = fgetcsv($handle, escape: '');
while (($row = fgetcsv($handle, escape: '')) !== false) {
yield array_combine($header, $row);
}
} finally {
fclose($handle);
}
}
$totals = [];
foreach (csvRows($file) as $sale) {
$totals[$sale['region']] = ($totals[$sale['region']] ?? 0) + (int) $sale['amount'];
}
arsort($totals);
print_r($totals);
unlink($file);
Output
Array
(
[South] => 300
[North] => 200
[West] => 50
)
Step-by-Step Explanation
csvRows()opens the file and yields one associative array per row. Only a single row is in memory at a time, so the same code handles a file with millions of rows.- The
finallyblock closes the file when iteration ends — normally, after abreak, or if an exception is thrown. - The aggregation loop does not know or care that rows are read lazily; it simply iterates.
Common Mistakes
Expecting the Function Body to Run Immediately
Effect: Side effects (echo, logging, validation) happen only when iteration starts.
Fix: Remember that calling a generator function only creates the generator.
Iterating a Generator Twice
Effect: "Cannot traverse an already closed generator".
Fix: Create a new generator, or store the values in an array.
Losing Values With iterator_to_array()
Effect: Duplicate keys overwrite earlier values.
Fix: Pass false as the second argument.
Using Generators Where Random Access Is Needed
Effect: count() and $gen[5] do not work on generators.
Fix: Use arrays when you need counting, indexing, or sorting.
Best Practices
- Use generators for large or infinite sequences and for streaming files, query results, and API pages.
- Declare the return type
Generator(oriterable) for clarity. - Clean up resources in
finallyinside generators. - Build reusable lazy steps (
map,filter,take) for data pipelines. - Convert to arrays only when the data must be reused or needs array features.
Official reference: https://www.php.net/manual/en/language.generators.php