3

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 ?

3
  • I think the documentation explains pretty clearly what advantages generators have over iterators or array based approaches. What in there exactly is it you struggle with? Commented Apr 29, 2017 at 9:02
  • simple and clear explanation with exemples from experienced :) Commented Apr 29, 2017 at 9:12
  • The documentation does provide pretty good examples, actually. Commented Apr 29, 2017 at 9:13

1 Answer 1

7

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.