Advertisement
Advanced PHP, Generators & Iterators

What are the limitations of PHP generators compared to regular arrays, particularly around rewinding and multiple iteration passes?

Short answer

Unlike a regular array, a PHP generator can typically only be iterated over once from start to finish, since it represents a single, forward only sequence of values that are computed lazily as they are requested, meaning attempting to iterate over the same generator instance a…

Save PHP mock interview
Advertisement
AModel answer
Unlike a regular array, a PHP generator can typically only be iterated over once from start to finish, since it represents a single, forward only sequence of values that are computed lazily as they are requested, meaning attempting to iterate over the same generator instance a second time, or explicitly calling rewind on a generator that has already started producing values, will throw an exception, which is an important limitation to keep in mind when designing code that might need to process the same sequence of data multiple times.
function numbers() {
    yield 1;
    yield 2;
}
$gen = numbers();
foreach ($gen as $n) { echo $n; }
foreach ($gen as $n) { echo $n; } // Throws an exception on second iteration
Real-world example
A developer debugging an unexpected exception discovers their code was attempting to loop over the same generator instance twice, and fixes the issue by calling the generator producing function again to create a fresh generator for the second iteration instead.
Likely follow-ups
  • Why can't a generator simply be rewound like an array pointer can?
  • What pattern should you use if you genuinely need to iterate over the same underlying data multiple times?
Related topics