Lesson contents

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

  1. Start with Call numbers()
  2. Do this Resume at each yield
  3. Result 1 → 2
The generator pauses at the first yield. The next iteration resumes the function and receives 2.
lesson.php
<?php
function numbers() {
    yield 1;
    yield 2;
}
foreach (numbers() as $n) {
    echo $n, PHP_EOL;
}
Output
1
2
Advertisements

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.

Fault code: −1 is skipped. First result: 4. Next result: 7.
Read valid counts as they arrive

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
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;
}
Output
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.

PHP language reference

Related tags

  • PHP
  • generators
  • yield
  • iterables