
Stop Loading Everything Into Memory: Lazy Iteration With PHP Generators
When you need to process a very large file — a multi-gigabyte CSV export, a big log dump, a stream of API records — the instinctive PHP code is also the wrong one.
The Wrong Reflex
$lines = file('huge-export.csv'); // reads the WHOLE file into an array
foreach ($lines as $line) {
process($line);
}
file() slurps the entire file into memory at once. On a 2 GB file this either exhausts your memory_limit or silently balloons RAM until the process is killed. The array holds every row simultaneously even though you only ever need one at a time.
Yield One Row at a Time
A generator is a function that can yield values one by one and suspend itself between each one. PHP keeps only the current row in memory, not the whole collection.
function readCsvRows(string $path): Generator
{
$handle = fopen($path, 'r');
if ($handle === false) {
throw new RuntimeException("Cannot open $path");
}
while (($row = fgetcsv($handle)) !== false) {
yield $row; // hand back ONE row, then pause
}
fclose($handle);
}
// Constant memory, no matter how big the file is:
foreach (readCsvRows('huge-export.csv') as $row) {
if ($row[0] === 'ERROR') {
logError($row);
}
}
The foreach pulls rows lazily. By the time you have seen the 10,000th row, the first 9,999 are already gone from memory. Peak usage stays flat.
Three Gotchas
Generators are not free lists. Three surprises bite almost everyone once.
- They are single-use. Once exhausted, iterating again yields nothing.
count($gen)does not work — a generator is notCountable. Need a second pass? Call the function again to get a fresh generator. - The body is lazy. Code inside the generator does not run until you start iterating. Building it with
$g = readCsvRows(...)opens no file yet — the first row is produced only when the loop begins. returnis not a value. Areturninside a generator is its final return value, reachable only via$gen->getReturn()after iteration finishes — it is never yielded.
function numbers(): Generator
{
yield 1;
yield 2;
return 'done'; // final return value, NOT a yielded item
}
$gen = numbers();
foreach ($gen as $n) {
echo $n; // prints 1, then 2
}
echo $gen->getReturn(); // prints "done"
When to Reach for It
Use a generator whenever the data is a sequence you can produce or consume item-by-item and you do not need random access or multiple passes: large file parsing, paginated API results turned into one stream, database result streaming, or infinite/very long sequences. For small, fixed collections a plain array is simpler and clearer — generators are a tool for scale, not a default.