Understanding PHP Generators and the yield Keyword

Generators let a PHP function produce a sequence of values lazily, one at a time, instead of building an entire array in memory upfront — a genuinely useful tool for processing large datasets.

function readLargeFile(string $path): Generator {
    $handle = fopen($path, 'r');
    while (($line = fgets($handle)) !== false) {
        yield trim($line);
    }
    fclose($handle);
}

// Processes one line at a time - never loads the whole file into memory
foreach (readLargeFile('access.log') as $line) {
    if (str_contains($line, 'ERROR')) {
        echo $line . "\n";
    }
}

Without a generator, processing a multi-gigabyte log file line by line would mean reading it into an array first — potentially exhausting memory. yield pauses execution at each value and resumes only when the next one is requested, keeping memory usage constant regardless of dataset size.