0

I just read through an example tutorial on using yield, and I have to say that I didn't understand it at all. I ran the example code, and it doesn't look like it's doing anything a regular forloop isn't able to do. It just iterate the numbers 1,2,3 like a regular forloop would do, except it's using a generator to do it? I don't understand at all, so if anyone can, please explain to me the differences between using a generator and a regular forloop.

<?php
function gen_one_to_three() {
    for ($i = 1; $i <= 3; $i++) {
        // Note that $i is preserved between yields.
        yield $i;
    }
}

$generator = gen_one_to_three();
foreach ($generator as $value) {
    echo "$value\n";
}
?>

Results:

1
2
3

Using just a forloop:

for ($i = 1; $i <= 3; $i++) {
echo $i;
}

Results:

1
2
3
jessica
  • 1,667
  • 1
  • 17
  • 35
  • `"In its simplest form, a yield statement looks much like a return statement, except that instead of stopping execution of the function and returning, yield instead provides a value to the code looping over the generator and pauses execution of the generator function."` - [PHP Generators Syntax](http://php.net/manual/en/language.generators.syntax.php) – Darren Oct 06 '15 at 02:07
  • @Darren Yeah. That's where I got this example from. – jessica Oct 06 '15 at 02:09
  • 1
    This may help you understand it better. [How to uses the "yield" keyword..](https://www.leaseweb.com/labs/2014/05/how-to-use-yield-keyword-php/) – Scotty C. Oct 06 '15 at 02:11

0 Answers0