tags:

views:

62

answers:

8

Hi all.

I usually write this:

if ($myvar == null)

but sometimes I read this:

if (null == $myvar)

I remember somebody told me the latter is better but I don't remember why.

Do you know which is better and why?

Thanks, Dan

+5  A: 

If you accidentally forget one of the =, the second one will give an error.

if ($myvar = null)

This will assign null to $myvar and perform the if check on the result.

if (null = $myvar)

This will try to assign the value of $myvar to null and give an error because you cannot assign to null.

SLaks
I see. That makes sense. Thanks!
Tom
A: 

It is not about the order, it is about avoiding accidental skipping one =, which will result in assignment instead of comparison. When using constant-first convention, accidental skipping will throw an error.

A.
A: 

I've seen the latter used to help avoid programmer errors such as:

if($myvar = null)

this will always return true, whereas

if(null = $myvar)

will throw an error.

fredley
No, the first one will return `null`, which evaluates to `false` in the boolean conversion, so this conditional will never pass. The other problem is that it will also set `$myvar` to `null`.
lonesomeday
A: 

you can use is_null() instead :)

Orbit
Not what he was asking, this is about operand order.
fredley
A: 

It doesn't really matter as long you don't forget to write == instead of =

Enrico Pallazzo
A: 

Using the assignment operator = in place of the equality operator == is a common mistake:

if($myvar = null)

which actually assigns null to $myvar. One way to get this logical error caught is to use the constant on the LHS so that if you use = in place of == you'll get an error as constants (null in this case) cannot be assigned values:

codaddict
+1  A: 

What this person may have alluded to was micro optimizations regarding conditional statements. For example, in the following, the second condition would not be evaluated as the first already failed.

if (1 == 0 && 1 == 1)

However, what you have will always be evaluated. Therefore order doesn't matter, and the convention mentioned already is the way to go.

Jason McCreary
A: 

Just as a sidenote, using the == operator to check for null can be somewhat bug-prone because PHP implicitly casts the second operand to the type of the first operand:

$test = false;

if ($test == null) echo 1;
if (null == $test) echo 1;

// Outputs 11

The is_null() function is safer since it doesn't involve any invisible typecasting magic:

$test = null;
if (is_null($test)) echo 1; // gets executed

$test = false; 
if (is_null($test)) echo 1;  // doesn't get executed
Saul