Search code examples
phpcomparison-operators

Does variables' order matter when doing == and === comparisons?


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'?)


Solution

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