PHP — Lazy iteration with generators
Use a generator to produce qualifying values one at a time from an iterable.
A simple example
Get two values from a generator
- Start with Call numbers()
- Do this Resume at each yield
- Result 1 → 2
<?php
function numbers() {
yield 1;
yield 2;
}
foreach (numbers() as $n) {
echo $n, PHP_EOL;
}
1 2
Yield positive readings on demand
A function containing yield returns a Generator. Its body advances as foreach requests values. Filtering can therefore operate on an iterable without building an intermediate array.
A visitor counter reports −1, then 4 and 7. A generator skips the failed count and yields each positive reading when the caller asks for it. The first valid count is 4 and the next one is 7.
Run the example
PHP 8 or later. Run these commands from the directory containing the example.
php lesson.php
<?php
declare(strict_types=1);
function positives(iterable $readings): Generator
{
foreach ($readings as $value) {
if ($value > 0) {
yield $value;
}
}
}
foreach (positives([-1, 4, 7]) as $value) {
echo $value, PHP_EOL;
}
4 7
The generator skips −1 and yields 4 and 7 to the caller. Each is printed on a separate line.
Try it yourself
What happens if the consumer breaks after the first value?
Check your answer
Only 4 is printed. The later reading is never requested.