Generators advanced

A generator in PHP is a function that yields values one at a time and keeps its place between calls. This lesson adds the three things a plain generator lacks: input from the caller, a final return value and delegation to another generator.

Send values in

By default data flows one way from yield to the loop. Calling send pushes a value back into the paused generator where yield works as an expression.

The value passed to send becomes the result of the current yield, so the generator can react to the caller on every step.

<?php function echoer(): Generator { $input = yield "ready"; while (true) { $input = yield "got " . $input; } } $gen = echoer(); $gen->rewind(); echo $gen->current(), PHP_EOL; $gen->send("hello"); echo $gen->current(), PHP_EOL;

php send.php

ready
got hello

The first value arrives without input, and the word hello came back through the paused yield and shaped the second value.

Return from generator

A generator can finish with a return value in addition to yielded items. The loop still ends normally and then getReturn reveals the final result.

This pattern fits totals, counts, and status codes computed while streaming values one by one.

<?php function countUp(int $max): Generator { for ($i = 1; $i <= $max; $i++) { yield $i; } return $max * 10; } $gen = countUp(3); foreach ($gen as $n) { echo $n, " "; } echo PHP_EOL; echo $gen->getReturn(), PHP_EOL;

php return.php

1 2 3
30

The loop saw the three yielded numbers and never the return value, which is available only after the generator finished.

Yield from

Yield from delegates part of the work to another generator. Values flow through as if written inline, which keeps large sequences split into small readers.

The outer generator pauses while the inner one runs, then continues after the last inner value.

<?php function inner(): Generator { yield 1; yield 2; } function outer(): Generator { yield 0; yield from inner(); yield 3; } foreach (outer() as $v) { echo $v, " "; } echo PHP_EOL;

php delegate.php

0 1 2 3

The inner values arrived between the two outer ones in the order the code names them.

Keys

Generators can yield keys together with values, just like arrays. String keys name each item, which makes logs and mapped data easier to follow.

Functions like iterator to array preserve those keys, so downstream code can stay unchanged.

<?php function pairs(): Generator { yield "a" => 1; yield "b" => 2; } foreach (pairs() as $k => $v) { echo $k, "=", $v, PHP_EOL; } echo json_encode(iterator_to_array(pairs())), PHP_EOL;

php keys.php

a=1
b=2
{"a":1,"b":2}

The loop read the names and the JSON shows that iterator_to_array() kept them as keys of the array.

Exercises

  1. Send three values in a row and print what the generator answers each time.
  2. Return the count of yielded items from a generator and print it after the loop.
  3. Delegate to two generators from one outer function and print the whole sequence.
  4. Yield keys of the shape row-1 and print the array that iterator_to_array() gives back.
  5. Explain the difference between send() and the value a generator yields.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does send() do to a paused generator?

    Answer

    It makes the value the result of the current yield

    The paused yield becomes an expression whose value is what the caller sent.

  2. How is the return value of a finished generator read?

    Answer

    With getReturn() after the loop ends

    The return value never appears as a yielded item; getReturn() reports it once the generator finished.

  3. What does yield from $inner do?

    Answer

    It forwards every value of the inner generator through the outer one

    The outer generator delegates to the inner one and continues after its last value.

  4. What does iterator_to_array() do with the keys of a generator?

    Answer

    It keeps them as array keys

    The keys become the keys of the resulting array, which is why JSON output keeps the names.

  5. What does this program print? <?php function echoer(): Generator { $input = yield "ready"; while (true) { $input = yield "got " . $input; } } $gen = echoer(); $gen->rewind(); echo $gen->current(); $gen->send("hello"); echo $gen->current();

    Answer

    readygot hello

    The first current() gives ready and the send() makes the next value got hello.

  6. What does this program print? <?php function countUp(int $max): Generator { for ($i = 1; $i <= $max; $i++) { yield $i; } return $max * 10; } $gen = countUp(3); foreach ($gen as $n) { echo $n; } echo $gen->getReturn();

    Answer

    12330

    The loop prints the three numbers and getReturn() appends the value 30.

  7. What does this program print? <?php function inner(): Generator { yield 1; yield 2; } function outer(): Generator { yield 0; yield from inner(); yield 3; } foreach (outer() as $v) { echo $v; }

    Answer

    0123

    The outer value comes first, then the two inner ones, then the last outer value.

  8. What does this program print? <?php function pairs(): Generator { yield "a" => 1; yield "b" => 2; } foreach (pairs() as $k => $v) { echo $k, $v; }

    Answer

    a1b2

    Each turn hands the key and the value, and the two echoes print them next to each other.

  9. What does this program print? <?php function pairs(): Generator { yield "a" => 1; yield "b" => 2; } echo json_encode(iterator_to_array(pairs()));

    Answer

    {"a":1,"b":2}

    The string keys survived the conversion, so JSON writes them as object members.

  10. Why can a generator not be iterated twice?

    Answer

    Because it throws away its values after each turn and cannot rewind a finished one

    The values are produced on demand, and after the last one the generator is finished for good.

The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.

Article author: Arthur Isaev