Advertisement
Beginner PHP, Generators & Iterators

What is a generator in PHP, and how does the yield keyword let a function produce a sequence of values without building an entire array in memory at once?

Short answer

A generator is a special kind of function that uses the yield keyword to produce a sequence of values one at a time, pausing its execution after each yield and resuming exactly where it left off the next time a value is requested, which is especially valuable for working with…

Save PHP mock interview
Advertisement
AModel answer
A generator is a special kind of function that uses the yield keyword to produce a sequence of values one at a time, pausing its execution after each yield and resuming exactly where it left off the next time a value is requested, which is especially valuable for working with large datasets since the generator only computes and holds one value in memory at a time rather than building and storing an entire array upfront.
function countTo($max) {
    for ($i = 1; $i <= $max; $i++) {
        yield $i;
    }
}
foreach (countTo(5) as $number) {
    echo $number;
}
Real-world example
A log file processing script uses a generator to yield one line at a time from a massive multi gigabyte file, keeping memory usage low regardless of how large the file actually is, rather than loading the entire file into an array first.
Likely follow-ups
  • What is the memory difference between a generator and a function that returns a full array?
  • Can you use a foreach loop directly on a generator, just like on a regular array?
Related topics