0

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

1
  • 1
    $i =+ $ctr is the same as $i = $ctr. + some number is essentially a no-op. Commented Oct 13, 2014 at 14:09

2 Answers 2

1

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

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

4 Comments

I agree with this, but why 1222222, and not 1111111??
you assign $i as $num1 in the first iteration, and you call it with 1 as a value for $num1
1 is the default value in case of not provided; Remove =1 (so function myfun($num1, $num2, $ctr)) in the loop definition, same behavior!!!
In the first iteration $i is equal to $num1, that's the first part of the for(). In the second iteration (and all others), it will be set to $ctr (which is 2). So you get one loop of $i being 1, and all the next ones where it will be 2. The loop doesn't finish, because $i <= $num2 is never true.
1
$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.

1 Comment

@Jean-ChristopheVerhulst Don't blame the parser. Nothing to complain for here - infinite loop is a valid syntactic construct. And here + symbol is interpreted as unary plus operator, i.e. $x = 10 and $x = +10 are semantically equivalent. Parser can't know that you instead of unary plus operator wanted to write compound assignment operator. So ...

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.