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?


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.


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

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Solution 2

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

Solution 3

Compare results from this to ifs.

 echo "Test '1abc' == 1 - ";
 if ('1abc' == 1) {
    echo 'ok';
 } else {
    echo 'fail';

 echo "\nTest '1abc' === 1 - ";
 if ('1abc' === 1) {
    echo 'ok';
 } else {
    echo 'fail';

Then read this page it’s very interesting lecture 😉

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply