php weird priority of == over null coalesce operator

142
May 01, 2018, at 04:23 AM

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') { 
    ...
}
Answer 1

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!

READ ALSO
Using domxpath to parse a some complex nested html

Using domxpath to parse a some complex nested html

I'm having issues figuring out how to get certain elements of text out of a rather more complex html page than any I can find examples of online

124
Symfony Query Builder partial query throwing circular reference error

Symfony Query Builder partial query throwing circular reference error

In my Symfony 4 application there is an API endpoint from which I need information about last Post from a given Thread and Author of this particular PostThis should be the structure of a reponse

176
convert series of json objects to single json object

convert series of json objects to single json object

I have a json file which has series of json arrays

172
Check if not url in validator laravel

Check if not url in validator laravel

I have 2 inputs with social accounts, I need get login this social accountsI need deny write links in this inputs

176