The Yield Keyword

suggest change

A yield statement is similar to a return statement, except that instead of stopping execution of the function and returning, yield instead returns a Generator object and pauses execution of the generator function.

Here is an example of the 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:
class Generator (0) {
}

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:


Generators:
* The Yield Keyword

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
32 Generators
35 UTF-8
36 URLs
38 PHPDoc
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR