Reputation: 1936
I am trying to get the logic of php generator functions, what i got so far is that is that a generator function is exactly like a normal function but you can use the keyword yield as many times as it needs to in order to provide the values to be iterated over. and this cannot be done by the return keyword .
is it like returning an array ?
where do we need generators ?
Upvotes: 3
Views: 807
Reputation: 780909
A generator allows you to loop over a sequence of values without first creating an array to hold them all. This is useful if the sequence never ends (you use break
to get out of the loop when some criteria is reached) or if it would take a long time or use lots of memory to create all the array elements.
Instead of collecting all the values into an array, the generator calculates each value as it's needed, and uses yield
to produce this value.
There's an example in the documentation showing a variation of the range()
function that uses a generator, so you can process very large ranges without using lots of memory.
Upvotes: 7