PHP null coalesce + ternary operators strange behavior

Viewed 462

I'm facing unexpected behavior when using new PHP7 null coalesce operator with ternary operator.

Concrete situation(dummy code):

function a()
{
    $a = 1;
    $b = 2;
    return $b ?? (false)?$a:$b;
}

var_dump(a());

The result is int(1).

Can anybody explain me why?

3 Answers

Your spaces do not reflect the way php evaluates the expression. Note that the ?? has a higher precedence than the ternary expression.

You get the result of:

($b ?? false) ? $a : $b;

Which is $a as long as $b is not null or evaluates to false.

Examine the statement return $b ?? (false)?$a:$b;

This first evaluates $b ?? (false) whose result is then passed to ? $a:$b;

$b ?? (false) means give the first not null and isset value, which in this case is $b

Since $b = 2, which is a true-ish value, above expression becomes:

return ($b) ? $a : $b which returns value of $a which is int(1)

This whole thing will make better sense if you think of original return statement as:

return ($b ?? (false)) ? $a : $b;

We dont need to add the additional brackets because ?? is evaluated before ?

return $b ?? (false)?$a:$b; // will return 1

return $b ?? ((false)?$a:$b); // will behave as you wanted
Related