Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

Generator

The object returned by a function containing `yield`.

Syntax

function name(): Generator { yield $value; }

Return value

GeneratorAn object to loop over with `foreach`, with the `current()`, `next()`, `send()` and `getReturn()` methods.

Examples

Values are computed one at a time:

<?php
 
function countdown(int $from): Generator
{
    while ($from > 0) {
        yield $from--;
    }
}
 
foreach (countdown(3) as $number) {
    echo $number, ' ';
}

Output:

3 2 1

The return value after iteration:

<?php
 
function sumOf(array $numbers): Generator
{
    $sum = 0;
 
    foreach ($numbers as $n) {
        $sum += $n;
        yield $n;
    }
 
    return $sum;
}
 
$generator = sumOf([1, 2, 3]);
foreach ($generator as $n) {}
 
echo $generator->getReturn();

Output:

6

Notes

A generator can be iterated only once: a second foreach throws an exception. Call the function again for a new pass.

See also

  • iterator_to_array — Turns an iterator or a generator into an array.
  • range — Creates an array holding a sequence of values.
  • Closure — The class of anonymous functions and closures.

Related recipes

In the tutorial

  • Generators — Generators in PHP — the yield keyword, saving memory, keys, infinite sequences and reading large files.

Thanks for reading!

Donate to the site — we work hard for you.