Generators use yield to produce values one at a time instead of building a full array at once. This saves memory when working with large datasets or files. Use them for reading big CSV files or streaming query results.
Generators
// Generator — lazy iteration (memory efficient)
function fibonacci(): Generator {
[$a, $b] = [0, 1];
while (true) {
yield $a;
[$a, $b] = [$b, $a + $b];
}
}
$fib = fibonacci();
for ($i = 0; $i < 10; $i++) {
echo $fib->current() . " ";
$fib->next();
}
// 0 1 1 2 3 5 8 13 21 34
// Yield key => value
function indexedLines(string $file): Generator {
$handle = fopen($file, "r");
$line = 1;
while (!feof($handle)) {
yield $line++ => fgets($handle);
}
fclose($handle);
}
foreach (indexedLines("data.txt") as $num => $line) {
echo "$num: $line";
}