1 min read

PHP Generators

Generators provide an easy way to implement simple iterators without the overhead or complexity of implementing a class that implements the Iterator interface.

A generator allows you to write code that uses foreach to iterate over a set of data without needing to build an array in memory, which may cause you to exceed a memory limit.


1. The yield Keyword

A generator function looks just like a normal function, except that instead of returning a value, a generator yields as many values as it needs to.

When a generator function is called, it returns an object that can be iterated over.

function simpleGenerator() {
    yield 1;
    yield 2;
    yield 3;
}

foreach (simpleGenerator() as $value) {
    echo $value . "\n";
}

2. Why Use Generators? (Memory Efficiency)

The primary benefit is memory usage. If you need to iterate over a large range of numbers or lines in a file, an array stores them all in memory at once. A generator yields them one by one.

Using an Array (High Memory)

function getRange($max) {
    $array = [];
    for ($i = 0; $i < $max; $i++) {
        $array[] = $i;
    }
    return $array;
}

Using a Generator (Low Memory)

function getRangeGenerator($max) {
    for ($i = 0; $i < $max; $i++) {
        yield $i;
    }
}

// This uses constant memory regardless of $max
foreach (getRangeGenerator(1000000) as $number) { ... }

programming/php/php programming/php/php-loops