Generators with yield
A generator produces a series of values without building the whole series in memory. In PHP the yield keyword turns a function into one, and a foreach loop takes the values one at a time.
Your first generator
A generator is a function that contains yield. Instead of returning once,
it produces values one by one while the caller loops with foreach.
Each iteration resumes the function right after the previous yield.
<?php function numbers(int $max): Generator { for ($i = 1; $i <= $max; $i++) { yield $i; } } foreach (numbers(3) as $n) { echo $n, PHP_EOL; }
php yield.php
1
2
3
The loop of the caller asks for the next value three times, and the function advances its own $i each time. Nothing runs before the first iteration, so a generator call alone has no effect.
Why memory stays flat
A normal function building a million item array must hold all values at once.
A generator holds only the current value, so memory use stays flat while the count grows.
This makes generators ideal for reading large files and paginated API responses line by line.
<?php function lines(string $path): Generator { $fh = fopen($path, "r"); while (($line = fgets($fh)) !== false) { yield trim($line); } fclose($fh); } $path = __DIR__ . "/data.txt"; file_put_contents($path, "alpha\nbeta\n"); foreach (lines($path) as $line) { echo $line, PHP_EOL; } unlink($path);
php lines.php
alpha
beta
The program writes its own two-line file with file_put_contents(), so the example needs no other file on disk. The reader opens the handle with fopen(), takes each line with fgets(), trims it with trim() and closes it with fclose(); the last unlink() removes the temporary file.
Yield keys and values
Yield accepts an optional key before the value arrow. Callers then receive pairs just
like from a normal array, which keeps downstream code unchanged.
Keys can be IDs, slugs, or line numbers that explain each value.
<?php function users(): Generator { yield 1 => "Ada"; yield 2 => "Grace"; } foreach (users() as $id => $name) { echo $id, " ", $name, PHP_EOL; }
php keys.php
1 Ada
2 Grace
The key travels with the value, so the caller reads both without a counter of its own. A yield without a key numbers its values from zero, the way an array does.
When not to use them
Generators are forward only and cannot rewind without replaying the function.
Counting, sorting, or random access needs a real array instead.
Use a generator for streaming and an array for repeated passes over small data.
<?php function numbers(int $max): Generator { for ($i = 1; $i <= $max; $i++) { yield $i; } } $gen = numbers(5); var_dump(count(iterator_to_array($gen))); var_dump(is_countable(numbers(5)));
php when.php
int(5)
bool(false)
count() cannot measure a generator, which is_countable() reports as false. iterator_to_array() runs the generator to its end and returns the five values as an array, which the count can measure.
Exercises
- Change numbers(3) to numbers(0) and run it. How many lines appear?
- Make the file reader yield the line number as the key as well as the text.
- Write a generator that yields every second number up to 10 and print it with a foreach loop.
- Call count() on a generator without iterator_to_array() and read the error.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What is a generator?
Answer
A function with
yieldthat produces values one at a timeThe yield keyword turns the function into a generator that hands out one value per iteration.
-
What happens when the caller asks for the next value?
Answer
The function resumes right after the previous yield
The state of the function is kept between iterations, so the loop continues where it stopped.
-
Why does the memory use of a generator stay flat?
Answer
It holds only the current value
One value exists at a time, however long the series is.
-
What does
yieldaccept before the value arrow?Answer
An optional key
The key is handed to the caller along with the value, as an array key would be.
-
What does this program print?
<?php function numbers(int $max): Generator { for ($i = 1; $i <= $max; $i++) { yield $i; } } foreach (numbers(3) as $n) { echo $n, PHP_EOL; }Answer
1 / 2 / 3
The loop yields 1, 2 and 3, and each one prints on its own line.
-
What does this program print?
<?php function users(): Generator { yield 1 => "Ada"; yield 2 => "Grace"; } foreach (users() as $id => $name) { echo $id, " ", $name, PHP_EOL; }Answer
1 Ada / 2 Grace
Each yield gives a key and a value, and the echo prints both on one line.
-
What does this program print?
<?php function numbers(int $max): Generator { for ($i = 1; $i <= $max; $i++) { yield $i; } } $gen = numbers(5); var_dump(count(iterator_to_array($gen))); var_dump(is_countable(numbers(5)));Answer
int(5) / bool(false)
iterator_to_array builds the array of five values, while a fresh generator is not countable.
-
What does this program print?
<?php function pair(): Generator { yield "a"; yield "b"; } foreach (pair() as $i => $v) { echo $i, $v; }Answer
0a1b
A yield without a key gets the next integer key, so the keys are 0 and 1.
-
What does this program print?
<?php function numbers(): Generator { yield 1; yield 2; } $gen = numbers(); try { count($gen); } catch (TypeError $e) { echo "TypeError"; }Answer
TypeError
A generator is not countable, so count() throws a TypeError that the catch prints.
-
Can a generator loop over its values a second time after it has finished?
Answer
No, it is forward only and has to be built again
The function has run to its end, so a second pass needs a new call to the generator function.
The code on this page was run with PHP 8.5.13 (php -v) in Alpine Linux, with the commands shown above.
Article author: Arthur Isaev