Wikis & learning

Iterate over a generated sequence

A generator yields one value at a time. The consuming code can accept an iterable without needing the entire sequence in an array.

A generator yields one value at a time. The consuming code can accept an iterable without needing the entire sequence in an array.

Walkthrough

Call the generator function, then use foreach to request its values. Each yield suspends execution and preserves the local loop state until the next value is requested.

PHP example

<?php
function numberedPages(int $last): iterable {
    for ($i = 1; $i <= $last; $i++) {
        yield 'p' . $i;
    }
}
foreach (numberedPages(3) as $page) {
    echo $page, PHP_EOL;
}

Expected output

p1
p2
p3

Change and check

Change the loop bounds and stop the consumer after two values. Observe which values get printed and which are never requested.