Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP null coalesce + ternary operators strange behavior

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?

like image 494
Aldos Avatar asked Jan 03 '23 09:01

Aldos


1 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.

like image 106
jeroen Avatar answered Jan 05 '23 22:01

jeroen