typestar

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

  1. yield inside a function makes it return a Generator.
  2. naturals is infinite; foreach pulls values until the break.
  3. yield from delegates to another iterable mid-stream.
  4. iterator_to_array drains a generator; false drops reused keys.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Modern touches, step 22 of 27 in Language basics.

← Previous Next →

Generators in other languages