function csvReader(string $file): Generator {
$fh = fopen($file, 'r');
while (!feof($fh)) {
yield fgetcsv($fh);
}
fclose($fh);
}
foreach (csvReader('million_rows.csv') as $row) {
process($row); // only one row in memory
}An array of millions of rows takes hundreds of MB. A generator uses O(1) memory regardless of size. Execution is lazy: the next value is computed only when requested.
yield from delegates execution to another generator or iterable — useful for composing generators.