Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does variables' order matter when doing == and === comparisons? [duplicate]

Does it really matter to put variables after == or === when doing comparisons?

if (null == $var) {

}

if ($var == null) {

}

I've constantly seen coders prefer this way, is it for speed difference?

Updates:

Sorry I didn't make my question clear, what I want to know is not the different between == and ===, but expressions like null == $var and $var == null, so I've changed the code example.


Conslusion:

No functional or performance difference. Some consider it a best practice or simply a coding style. BTW it has a cool name: Yoda Conditions :)

FYI: PHP error messages use this style, e.g.

PHP Fatal error:  Cannot use isset() on the result of an expression (you can use "null !== expression" instead)

Don't know why this question is marked duplicated to (The 3 different equals) not (What's the difference between 'false === $var' and '$var === false'?)

like image 606
samluthebrave Avatar asked Oct 14 '13 01:10

samluthebrave


2 Answers

It prevents typos which cause very hard to debug bugs. That's in case you accidentally write = instead of ==:

if ($var == null)  # This is true in case $var actually is null
if ($var =  null)  # This will always be true, it will assign $var the value null

Instead, switching them is safer:

if (null == $var)   # True if $var is null
if (null =  $var)   # This will raise compiler (or parser) error, and will stop execution.

Stopping execution on a specific line with this problem will make it very easy to debug. The other way around is quite harder, since you may find yourself entering if conditions, and losing variable's values, and you won't find it easily.

like image 102
micromoses Avatar answered Sep 26 '22 20:09

micromoses


I think that the following code will explain it:

echo (( 0 == NULL ) ? "0 is null" : "0 is not null")  ."\n";
echo  (0 === NULL) ? "0 is null" : "0 is not null"  ;

it will output:

0 is null
0 is not null

The === operator checks for both value and type, but 0 is a number while NULL is of type NULL

The == operator checks only for value and zero can be casted to "false" or "null" hence the "truthy" that we get for the first line

like image 43
Nir Alfasi Avatar answered Sep 23 '22 20:09

Nir Alfasi