PHP has a great mechanism to create iterators in a compact fashion. This type of iterator comes with some severe limitations; they are forward only and cannot be rewound. Indeed, even to simply start an iterator from the start, you must rebuild the generator. In essence, this is a forward-only iterator.
A function that uses the yield
keyword instead of the return
keyword. This will act in the same way as a return
statement, but it will not stop the execution of that function. A generator function can yield
data as many times as you please.
When you populate an array with values, those values must be stored in memory which can cause you to exceed your PHP memory limit or require a significant amount of processing time for the generator. When you put the logic in a generator function, that overhead does not exist. The generator function may merely yield as many results as it needs; there's no need to prepopulate an array first.
Here is a simple generator that will var_dump
a string...