The Yield Keyword

suggest change

A function that uses yield returns a Generator when it is called. Each yield produces a value and pauses the generator until the caller asks for the next value.

Here is an example of a range function, written as a generator:

function gen_one_to_three() {
    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $i;
    }
}

You can see that this function returns a Generator object by inspecting the output of var_dump:

var_dump(gen_one_to_three());

/* Outputs:
object(Generator)#1 (1) {
  ["function"]=>
  string(16) "gen_one_to_three"
}
*/

Yielding Values

The Generator object can then be iterated over like an array.

foreach (gen_one_to_three() as $value) {
    echo "$value\n";
}

The above example will output:

1
2
3

Yielding Values with Keys

In addition to yielding values, you can also yield key/value pairs.

function gen_one_to_three() {
    $keys = ["first", "second", "third"];

    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $keys[$i - 1] => $i;
    }
}

foreach (gen_one_to_three() as $key => $value) {
    echo "$key: $value\n";
}

The above example will output:

first: 1
second: 2
third: 3

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents