Search code examples
phpternary-operatornull-coalescing-operator

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?


Solution

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