Reading — step 1 of 6
Learn
~1 min readReuse Patterns
Generators produce a sequence of values lazily, one at a time. Use yield instead of return:
function range_gen(int $start, int $end): \Generator {
for ($i = $start; $i <= $end; $i++) {
yield $i;
}
}
foreach (range_gen(1, 5) as $n) {
echo $n . "\n";
}
range_gen(1, 1_000_000) allocates almost no memory — it generates each value on demand. Compare to range(1, 1_000_000) which allocates a million-element array.
yield with keys:
function wordCounts(string $text): \Generator {
foreach (explode(' ', $text) as $w) {
yield $w => strlen($w);
}
}
foreach (wordCounts('the cat ran') as $word => $len) { ... }
yield from — delegate to another generator (like Python's):
function tree(): \Generator {
yield 1;
yield from subtree(); // yields all subtree's values
yield 99;
}
Common use cases:
- Reading large files line by line:
yield $lineinside afgetsloop - Lazy filtering chains
- Pagination — yield each page's items without holding them all
Generators implement Iterator so they work in foreach directly.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…