Generators in PHP
Functions that produce values lazily, one yield at a time.
<?php
// generators produce values lazily, one yield at a time
function naturals(): Generator {
for ($n = 1; ; $n++) {
yield $n;
}
}
foreach (naturals() as $n) {
if ($n > 5) break;
echo $n * $n, "\n";
}
// yield from delegates to another iterable
function letters(): Generator {
yield from ['a', 'b'];
yield 'c';
}
echo implode('-', iterator_to_array(letters(), false)), "\n";
How it works
yieldinside a function makes it return aGenerator.naturalsis infinite;foreachpulls values until thebreak.yield fromdelegates to another iterable mid-stream.iterator_to_arraydrains a generator;falsedrops reused keys.
Keywords and builtins used here
asbreakechofalseforforeachfunctionifimplodeiterator_to_arraylettersnaturalsyield
The run, in numbers
- Lines
- 19
- Characters to type
- 378
- Tokens
- 82
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 61 seconds.
Step 1 of 3 in Modern touches, step 22 of 27 in Language basics.