×

php · level 3 · unit 7 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Chain generators into a , one value flowing at a time.

A generator can take another generator as its input. Chain a few and you have a pipeline: one step reads values, the next keeps the useful ones, the next reshapes them. Each value flows through every step before the next one is even read.

yield $key => $value hands out a key as well, ready for foreach ($rows as $key => $value). hands out every value of another generator or array. A generator can even run forever, because it only works when asked, so stop the loop with break.

<?php
function readings(): Generator { yield from [12, -3, 15, 99, 14]; }
function valid(iterable $values): Generator {
    foreach ($values as $value) {
        if ($value >= 0 && $value <= 40) {
            yield $value;
        }
    }
}
function inFahrenheit(iterable $values): Generator {
    foreach ($values as $c) { yield "{$c}C" => ($c * 9 / 5 + 32) . "F"; }
}
foreach (inFahrenheit(valid(readings())) as $celsius => $fahrenheit) {
    echo "$celsius is $fahrenheit\n";
}

The type iterable accepts an array or a generator, so each step works with either.