Generators & Lazy Evaluation with yield

Generators & Lazy Evaluation with yield in PHP: --- At a busy bakery counter there is a little red dispenser bolted to the wall.


The Analogy: The Take-a-Number Dispenser at a Bakery

At a busy bakery counter there is a little red dispenser bolted to the wall. You pull the paper tab, it tears off the next number -- 47, say -- and inside it quietly clicks forward to 48. It has not pre-printed a thousand tickets and stacked them on the floor. It holds only its current position and produces the next number the instant someone pulls the tab. Pull again and you get 48, and the mechanism advances once more. Nothing exists until the moment it is asked for.

That pull-on-demand behaviour is exactly what a generator is. A generator function does not compute all of its values up front and hand back a finished array. It produces one value each time the consumer asks for the next, and between pulls it sits completely frozen, remembering precisely where it was in its own code. The dispenser remembers one number; a generator remembers one paused execution -- every local variable, and the exact statement it was about to run next.

This laziness is the entire point. A single small dispenser can serve a bakery all day because it never needs to store every number it will ever issue, only the next one. In the same way a generator can represent a sequence of a billion items, or even an endless one, in a fixed sliver of memory, because it only ever materialises the single value currently being handed out. The rest of the sequence is not sitting in memory waiting; it does not exist yet, and most of it never will if the consumer stops early.

The dispenser also has firm limits, and generators inherit every one of them. You cannot push a torn ticket back into the slot and have it re-issued -- the sequence only ever moves forward. You cannot ask the dispenser what number it will show in an hour without actually pulling that many tabs. And one dispenser serves one shared sequence: two counters that unknowingly share it will interleave their numbers and confuse every customer. Treat a generator as if it were rewindable, or countable in advance, or safe to iterate twice, and you will walk straight into exactly these walls.


Syntax or Core Structure

A function becomes a generator the moment it contains the yield keyword. Calling it does not run the body; it returns a Generator object. The body only advances when you iterate, and each yield hands one value to the consumer and pauses.

<?php
declare(strict_types=1);

function countTo(int $n): Generator {
    for ($i = 1; $i <= $n; $i++) {
        yield $i;                 // hand out $i, then pause here
    }
}

$parts = [];
foreach (countTo(3) as $v) { $parts[] = $v; }
echo 'count: ' . implode(', ', $parts), "\n";

// yield can also produce key => value pairs.
function labelled(): Generator {
    yield 'a' => 1;
    yield 'b' => 2;
}

$pairs = [];
foreach (labelled() as $k => $v) { $pairs[] = "{$k}={$v}"; }
echo 'keyed: ' . implode(', ', $pairs), "\n";

Output:

count: 1, 2, 3
keyed: a=1, b=2

Reading countTo, it looks like an ordinary loop, but the yield changes everything: the function pauses at each yield $i, hands $i to the foreach, and resumes from that exact line when the loop asks for the next value. The keyed form yield $key => $value mirrors an associative array, letting a generator drive a foreach ($gen as $k => $v) just like an array would. At no point does countTo build an array of all three numbers; it produces them one at a time.


Technical Depth: Laziness, Delegation, and the Trade-offs

Array versus generator

A generator is not always the right choice. The table below shows where each wins.

PropertyFull arrayGenerator
MemoryHolds every element at onceHolds one element at a time
EvaluatedEagerly, when builtLazily, as each value is pulled
RewindableYes, iterate as often as you likeNo, forward-only and single-use
Random accessYes, by key or indexNo, must walk in order
count()Cheap, known instantlyRequires consuming the whole thing

The rule of thumb: use an array when the data is small, needs random access, or will be iterated more than once; use a generator when the data is large, streamed, or possibly infinite, and you only need a single forward pass.

Laziness you can see

Because a generator only runs far enough to produce the next value, you can watch production and consumption interleave. This generator would run forever, yet the consumer stops it after two values.

<?php
declare(strict_types=1);

function makeForever(): Generator {
    $i = 1;
    while (true) {              // never terminates on its own
        echo "make {$i}\n";    // printed the moment this value is produced
        yield $i;
        $i++;
    }
}

foreach (makeForever() as $v) {
    echo "got {$v}\n";
    if ($v === 2) {
        break;                  // stop pulling; the generator freezes for good
    }
}

Output:

make 1
got 1
make 2
got 2

The interleaving is the proof of laziness. make 1 prints, then got 1, then make 2, then got 2 -- production and consumption take turns. An eager function that returned an array would have to loop forever before returning anything, hanging the program. The generator instead produces just enough, and break leaves it frozen, never running the third iteration.

Delegating with yield from

A generator can hand off to another iterable with yield from, splicing that source's values into its own stream. It is the clean way to compose generators.

<?php
declare(strict_types=1);

function inner(): Generator {
    yield 1;
    yield 2;
}

function outer(): Generator {
    yield 0;
    yield from inner();   // splice inner's values in here
    yield 3;
}

$vals = [];
foreach (outer() as $v) { $vals[] = $v; }
echo 'delegated: ' . implode(', ', $vals), "\n";

Output:

delegated: 0, 1, 2, 3

yield from produced 0, then delegated to inner for 1 and 2, then resumed for 3. One caveat worth knowing: yield from preserves the keys of the inner iterable, so if both outer and inner yield integer keys starting at zero, those keys collide. When you only consume values through a foreach that ignores keys it does not matter, but if you collect into an array with iterator_to_array, the collisions silently overwrite entries unless you pass false as the second argument.

A generator can also return a value

Beyond the values it yields, a generator may end with a return, and that final value is fetched afterwards with getReturn(). This is the correct way to stream items and report a summary once the stream is exhausted -- and it is exactly what people reach for when they wrongly try to return a value they meant to yield.

<?php
declare(strict_types=1);

function scan(array $nums): Generator {
    $sum = 0;
    foreach ($nums as $n) {
        $sum += $n;
        yield "saw {$n}";   // streamed one at a time
    }
    return $sum;            // NOT yielded; available via getReturn()
}

$gen = scan([10, 20, 30]);
foreach ($gen as $line) {
    echo $line, "\n";
}
echo 'final total: ' . $gen->getReturn(), "\n";

Output:

saw 10
saw 20
saw 30
final total: 60

The three saw lines stream out of the foreach, and only after the loop has fully drained the generator can getReturn() be called to retrieve the 60. Calling getReturn() before the generator has finished throws, because the return has not been reached yet -- another reminder that a generator is a running computation you drive forward, not a container you inspect at will.


Real World Example: Streaming a Large Data Feed

The classic use for a generator is processing a data source too large to hold in memory all at once -- a multi-gigabyte log, a database cursor, an API that pages forever. The generator reads and parses one record at a time and hands it to the consumer, which keeps only a running aggregate. Here a generator yields parsed transaction rows while the consumer builds a small summary, never holding more than one row.

<?php
declare(strict_types=1);

// In production this would read a file or a DB cursor line by line.
// Each pull parses exactly one row, so memory stays flat regardless of size.
function readTransactions(array $rawLines): Generator {
    foreach ($rawLines as $line) {
        [$date, $amount] = explode(',', $line);
        yield ['date' => $date, 'amount' => (int) $amount];
    }
}

$rawLines = [
    '2026-01-01,100',
    '2026-01-02,250',
    '2026-01-03,75',
];

$count = 0;
$total = 0;
$large = 0;
foreach (readTransactions($rawLines) as $tx) {
    $count++;
    $total += $tx['amount'];
    if ($tx['amount'] >= 100) {
        $large++;
    }
}

echo "processed {$count} rows\n";
echo "total: {$total}\n";
echo "large (>=100): {$large}\n";

Output:

processed 3 rows
total: 425
large (>=100): 2

The consumer only ever holds one $tx plus three running counters, so the same code processes three rows or three billion with identical memory. The amounts sum to 425, and two of the three (100 and 250) clear the 100 threshold, so large is 2. Swap the hard-coded $rawLines array for a function that reads a file handle one line at a time and nothing else changes -- that substitutability is exactly why generators are the natural shape for streaming work.

The code is a faithful sketch, but it has a real robustness flaw that would surface on genuine data. The line [$date, $amount] = explode(',', $line) trusts every row to be perfectly formed. A blank line, a header row, or a value with an embedded comma would either raise an undefined-index warning or silently coerce garbage: (int) "abc" is 0, quietly poisoning the total with a zero instead of failing loudly. There is also a subtler trap in the shape of the design: because a Generator is single-use, you cannot iterate readTransactions($rawLines) a second time to compute a different aggregate -- a second foreach over the same generator object throws Cannot rewind a generator that was already run. A production version would validate each row before the cast and, if two passes are genuinely needed, either reopen the source per pass or accept the memory cost of an array.


Common Mistakes

  1. Expecting the body to run when you call the function. Calling a generator function runs none of its body; it just returns a Generator object. Any setup, validation, or side effect before the first yield does not happen until the first value is pulled.
  1. Trying to iterate a generator twice. A generator is a single forward pass. A second foreach over the same object throws Cannot rewind a generator that was already run. If you need multiple passes, collect to an array or recreate the generator.
  1. Calling count() on a generator. Generators do not implement Countable, and even if they did, counting means consuming. There is no cheap length; you must walk the whole sequence, which also exhausts it.
  1. Confusing return with yield. Inside a generator, return $x ends the sequence and does not yield $x. The returned value is only reachable afterwards through $gen->getReturn(). Writing return where you meant yield produces an empty-looking generator.
  1. Calling iterator_to_array without a second thought. Converting a generator to an array with iterator_to_array throws away the memory benefit that motivated the generator. Worse, with yield from and colliding integer keys, the default key-preserving mode silently overwrites entries -- pass false to reindex.
  1. Assuming random access. You cannot ask a generator for its fifth element without pulling the first four. If code needs indexing or keyed lookup, a generator is the wrong tool; use an array.
  1. Doing side effects before the first yield and expecting them eagerly. Because nothing runs until iteration begins, logging or opening a resource written above the first yield is deferred, which surprises people relying on it happening at call time.
  1. Sharing one generator between two consumers. A generator is a single cursor. Handing the same Generator object to two loops means the second sees only what the first left behind, because both advance the one shared position.
  1. Forgetting that yield from preserves inner keys. Delegating to another generator splices its keys as well as its values. When collecting the combined result, integer keys from the outer and inner sources can collide and clobber each other unless you reindex.

Best Practices

  • Reach for a generator when the data is large, streamed, or possibly infinite and you need only one forward pass; reach for an array when it is small, needs random access, or will be iterated more than once.
  • Type the return as Generator or the broader iterable so callers know they are getting a lazy sequence and can accept either a generator or an array.
  • Keep any expensive setup after the first yield in mind: if a resource must open at call time, open it outside the generator and pass it in.
  • Use yield from to compose generators rather than manually looping and re-yielding; it is clearer and forwards return values correctly.
  • When you must collect a generator into an array, do it deliberately with iterator_to_array, and pass false as the second argument if keys might collide.
  • Guard the consuming loop with a clear stop condition when the generator is infinite, so it cannot run away.
  • Validate and sanitise each yielded record inside the generator, so consumers can trust every item without re-checking.
  • Document that a generator is single-use where it is returned, so callers do not write a second foreach and hit a rewind error.

Practice Exercises

  1. Write a generator fibonacci(): Generator that yields Fibonacci numbers forever. Consume it with a foreach that breaks once a value exceeds 1000, and print the values collected.
  1. Write a generator that takes an array of raw key=value strings and yields each as a key => value pair using the keyed yield form. Iterate it to build a configuration array and print two of the settings.
  1. Compose two generators with yield from: one yielding the numbers 1 to 3, another yielding 4 to 6, and an outer generator that yields both in sequence. Collect the result with iterator_to_array passing false, and explain in a comment why the false is necessary.
  1. Take the streaming transaction example and make it robust: skip blank lines, validate that each row has exactly two comma-separated fields, and reject non-numeric amounts. Yield only valid rows and print how many lines were skipped.