PHP Reference ยท Functions and Classes
PHP generators: yield and yield from
Reference for PHP generators: yield, keys, send(), yield from, return values and the Generator class, with examples of lazy iteration and memory savings.
A generator is a function that contains the yield keyword. Calling it does not run the body. It returns a Generator object, and the body runs in slices as you iterate: each yield hands one value to the caller and pauses until the next value is requested.
Because values are produced one at a time, a generator can describe a huge or even infinite sequence while holding only the current item in memory. A Generator implements Iterator, so foreach works on it directly.
function countTo(int $n): Generator { for ($i = 1; $i <= $n; $i++) { yield $i; } } foreach (countTo(3) as $value) { echo $value, " "; // 1 2 3 }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.
Syntax
yield; // value null, auto key yield $value; // auto-incrementing integer key yield $key => $value; // explicit key $received = yield $value; // receives what send() passed in yield from <array|Traversable>; return $finalValue; // available through getReturn()
The Generator class (final, implements Iterator):
| Method | Description |
|---|---|
current(): mixed |
The current yielded value. Starts the generator if it has not run yet. |
key(): mixed |
The current key. |
next(): void |
Resumes the generator, discarding any sent value. |
send(mixed $value): mixed |
Sets the result of the current yield expression, resumes, and returns the next yielded value. |
throw(Throwable $e): mixed |
Throws the exception inside the generator at the paused yield, then returns the next yielded value. |
valid(): bool |
true while the generator has not finished. |
rewind(): void |
Runs to the first yield. Throws an exception if the generator has already advanced past it. |
getReturn(): mixed |
The value of return. Throws an exception if the generator has not finished or ended with an exception. |
Return value of the function: always a Generator object, whatever the body does, even if yield is never reached.
Errors: a generator can be traversed only once. Rewinding after the first yield or running a finished generator again throws an Exception.
Usage notes
- A function is a generator if
yieldappears anywhere in it, even in a branch that never runs. Its return type should beGenerator,Iterator,Traversableoriterable. - One pass only. A generator cannot be rewound once it has moved past the first yield. To iterate again, call the function again.
- Auto keys start at 0 and continue from the largest integer key used so far. Keys can repeat, so
iterator_to_array()loses values unless you passfalseforpreserve_keys. yield fromdelegates to another generator, array orTraversable. Keys of the inner source are preserved, which can collide with outer keys; useiterator_to_array(..., false)when you only need values. The expression's value is the inner generator's return value.- Memory. Reading a large file with a generator that yields one line at a time uses a few kilobytes, however big the file is.
send()runs the generator forward. The firstsend()on an unstarted generator first runs to the firstyield, discards that value, delivers your value to it, and continues to the next. Callcurrent()first if that surprises you.returninside a generator does not produce an iteration value. Read it withgetReturn()after the loop.- Generators can yield by reference when declared as
function &gen(). This is rarely needed. - Generators cannot be serialized or cloned.