php · level 3 · unit 7 · lesson 2
- meet it
- guess first
- your turn
- fix it
- 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.
guess first
This generator never ends. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
<?php
function ticketNumbers(): Generator {
$n = 1;
while (true) {
yield $n;
$n++;
}
}
foreach (ticketNumbers() as $ticket) {
if ($ticket > 3) {
break;
}
echo "Ticket $ticket\n";
}
echo "Queue closed\n";
your turn
Your turn. Find the long words.
Type a sentence in the first blank and a minimum word length in the second. iterator_to_array collects the pipeline's results into an array.
fix it
The day planner shows objects, not tasks. Fix it.
- The error says a
Generatorcould not be turned into a string. What doeswholeDayhand out on lines 5 and 6? yield morning()hands out the whole generator as one value. You want each of its values handed out in turn.- Change
yieldtoyield fromon lines 5 and 6, then run it.
nailed it
your generators work as a team now. :D
- A pipeline chains generators, each using the last one's output.
yield fromhands out every value of another generator.- An endless generator is safe, as long as the loop breaks.
new words in your collection
- pipeline
- yield from
This lesson isn’t saved. A free account remembers every lesson you finish.