Generators with yield
| Your first generator | |
| Why memory stays flat | |
| Yield keys and values | |
| When not to use them |
Your first generator
A generator is a function that contains yield. Instead of returning once,
it produces values one by one while the caller loops with foreach.
Each iteration resumes the function right after the previous yield.
function numbers(int $max): Generator { for ($i = 1; $i <= $max; $i++) { yield $i; } } foreach (numbers(3) as $n) { echo $n; }
Why memory stays flat
A normal function building a million item array must hold all values at once.
A generator holds only the current value, so memory use stays flat while the count grows.
This makes generators ideal for reading large files and paginated API responses line by line.
function lines(string $path): Generator { $fh = fopen($path, "r"); while (($line = fgets($fh)) !== false) { yield trim($line); } fclose($fh); } foreach (lines("data.txt") as $line) { echo $line; }
Yield keys and values
Yield accepts an optional key before the value arrow. Callers then receive pairs just
like from a normal array, which keeps downstream code unchanged.
Keys can be IDs, slugs, or line numbers that explain each value.
function users(): Generator { yield 1 => "Ada"; yield 2 => "Grace"; } foreach (users() as $id => $name) { echo $id; echo $name; }
When not to use them
Generators are forward only and cannot rewind without replaying the function.
Counting, sorting, or random access needs a real array instead.
Use a generator for streaming and an array for repeated passes over small data.
$gen = numbers(5); var_dump(count(iterator_to_array($gen))); var_dump(is_countable(numbers(5)));
Next: Forms: GET and POST
Article author: Arthur Isaev