Why does this PHP assignment in a loop always print the first value?

Viewed 34

I'm very confused as to the output of this small piece of test code:

<?php
$count = 0;
while ($fn_retval = do_the_thing($count) !== false) {
    print $fn_retval."\n";
    $count++;
}

function do_the_thing($count) {
    if ($count > 3) {
        return false;
    } else {
        return $count;
    }
}
?>

The output is:

$ php ./test.php 
1
1
1
1

So it is correctly performing 4 iterations but always printing the return value of the first iteration. I feel like I must have missed something really obvious because this makes no sense.

Can somebody explain what's going on here because it seems like I can't use that assign-and-check construct in the way I thought I could.

1 Answers

The problem is that the order in which

$fn_retval = do_the_thing($count) !== false

is evaluated. If you check the Operator Precedence, you will see that !== is a higher precedence than =, so it's evaluated as

do_the_thing($count) !== false

and the result is then assigned to $fn_retval.

To force the order you are after, use brackets to explicitly do the assignment first...

while (($fn_retval = do_the_thing($count)) !== false) {
Related