CodeBlanks Logo Icon CodeBlanks

The yield keyword

PHP course · Expert · Lesson 1/54

Learn to write a function that yields values and preserves state.

What is the yield keyword?

If a function contains the yield keyword, it is a generator function. When called, the code does not run; instead a Generator object is returned.

Each yield produces a value and execution pauses there. On the next request it resumes from where it left off. This way values are produced lazily; they are not all computed at once.

Iterating with foreach and keys

foreach iterates a Generator automatically: each loop fetches the next yield value. The form foreach ($gen as $value) gives the value.

To also produce a key, write yield $key => $value; then foreach ($gen as $k => $v) gives both.

Exercise Write the countUp generator

Write the countUp(int $from, int $to): \Generator function. Yield each number from $from to $to with yield. Then iterate countUp(2, 6) with foreach and print each number on its own line.

Show example solution
take int $from and int $to, return \Generator. Use a for loop to yield each number from $from to $to. Then iterate with foreach (countUp(2, 6) as $n) and echo $n . "\n";
Example solution:
<?php
function countUp(int $from, int $to): \Generator {
    for ($i = $from; $i <= $to; $i++) {
        yield $i;
    }
}

foreach (countUp(2, 6) as $n) {
    echo $n . "\n";
}

Test yourself

  1. What happens when you call a function containing yield?

    function gen() {
        yield 1;
        yield 2;
    }
    $g = gen();
    • The code runs immediately, the first value is returned
    • A Generator object is returned, the code does not run yet
    • An array is returned
    • An error is thrown
    Show answer

    A Generator object is returned, the code does not run yet — Correct. Calling a generator function returns a Generator object; the code does not advance to the first yield.

  2. yield in the countDown generator

    <?php
    function countDown(int $n): \Generator {
        while ($n > 0) {
            ____
            $n--;
        }
    }
    
    Show answer
    <?php
    function countDown(int $n): \Generator {
        while ($n > 0) {
            yield $n;
            $n--;
        }
    }
    
  3. Match the generator concepts

    yield
    Produces a value and pauses
    Generator
    Object returned by a yield function
    foreach
    Iterates a generator automatically
    yield $k => $v
    Yields a key-value pair

All lessons in Expert