Please help me understand PHP Generators

I’m studying for the ZCE exam and I am kinda stuck on what a PHP Generator is.

I read the php docs but I am not sure why a Generator is used. Seems like more code needs to be written to use a generator to do a simple task a forloop could do on its own.

I tried writing some code to see if it would make me understand it better but still I am not quite sure what the advantage of a generator is.

Here is the code I wrote:

    <?php

//Generator Function
function shownum($num){
	echo "Start Generator<br>";
	foreach($num as $key){
		yield $key;
	}
	echo "<br>End generator";
}

//Array
$nums = [1,2,3,4,5,6];

//Call the shownum function and pass the $num array.
$looped = shownum($nums);

//Loop through the $looped array.
foreach($looped as $key){
	echo $key;
}

Not sure why that would be better than this

<?php

//Array
$nums = [1,2,3,4,5,6];

//Loop through the $nums array.
foreach($nums as $key){
	echo $key;
}

You’re right in your example there is no real need to use generator.
As i understand them, they’re useful when you want to create really large array dynamically but don’t want store it in memory (due to memory limits).

There’s a pretty good explanation of them in this article (on sitepoint, of all places! :wink: ) I knew I’d seen it somewhere.

I think this does a very nice job of explaining them - the interesting part about generators is the ability to use the send() method to influence what the next value for it might be (see the Injecting Values section)

2 Likes

They are also very handy for infinite sequences, like if you wanted to walk over the values of the fibonacci sequence (see http://php.net/manual/en/language.generators.syntax.php#111969).

Awesome! Thanks a lot, this really helped. I Think I was just over thinking it.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.