phpoperator-precedencenull-coalescing-operator

Unexpected priority of comparison operator over null coalesce operator


I don't understand why this happens:

$var = 'x';
var_dump($var ?? '' == 'somevalue');

It outputs string(1) "x", while one should expect bool(false).

What is the reason behind this?


To imagine a use case, think for example at:

// I want to do something only if the optional_parameter is equal to somevalue
if($_GET['optional_parameter'] ?? '' == 'somevalue') { 
    ...
}

Solution

  • It's a matter of operator precedence, try:

    $var = 'x';
    var_dump(($var ?? '') == 'somevalue');
    

    More: http://php.net/manual/en/language.operators.precedence.php

    Plus a general advice: there is never too many parens! :) If you're not sure what is calculated first in a given language - use them!