PHP Yield keyword - loop iteration

I am using PHP generator and can't explain this behavior. This is the code I tried

<!-- language: PHP -->
<?php
function myfun($num1, $num2, $ctr = 1) {
    for ($i = $num1; $i <= $num2; $i =+ $ctr) {
        yield $i;
    }
}
echo 'Odd numbers: ';
foreach(myfun(1, 7, 2) as $num) {echo $num;};
?>

Can someone explain me this behavior using PHP yield, entering a infinite loop?

result: Odd numbers: 122222222222222222222222222222222...............

Note: $i += $ctr works as expected

result: Odd numbers: 1357

Upvotes: 0

Views: 422

Answers (2)

Jim
Jim

Reputation: 22656

$i =+ $ctr

=+ is not an operator. This will essentially do $i = $ctr.

The first time the loop occurs $i is set to $ctr, in this case this is 2. After this it is continually set to 2 and never goes higher. Hence the infinite loop. Use += instead.

Upvotes: 1

naneau
naneau

Reputation: 489

The problem lies in the =+ operation, you probably meant to type +=, which would do the trick:

<?php
function myfun($num1, $num2, $ctr = 1) {
    for ($i = $num1; $i <= $num2; $i += $ctr) {
        yield $i;
    }
}
echo 'Odd numbers: ';
foreach(myfun(1, 7, 2) as $num) {echo $num;};

Result: Odd numbers: 1357

Upvotes: 1

Related Questions