Skip to content
AgileLogics
5 min read

Generators & yield

Prerequisites: Closures & callbacks

A generator produces a sequence of values lazily, one at a time, instead of building a whole array in memory up front — essential when iterating something very large.

function countUpTo(int $n): Generator
{
    for ($i = 1; $i <= $n; $i++) {
        yield $i;
    }
}

foreach (countUpTo(1000000) as $number) {
    if ($number > 3) break;
    echo $number; // 1, 2, 3
}

Only the values actually consumed are ever computed — the loop above never generates the other 999,997 numbers, unlike returning a full array from range(1, 1000000) would.