9

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

Tom
  • 101
  • 3
  • 1
    This is a duplicate of http://stackoverflow.com/questions/271561/why-does-one-often-see-null-variable-instead-of-variable-null-in-c and many others – Harmen Oct 25 '10 at 13:54

6 Answers6

11

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
  • 868,454
  • 176
  • 1,908
  • 1,964
1

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.

NOtherDev
  • 9,542
  • 2
  • 36
  • 47
1

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
  • 71,546
  • 23
  • 135
  • 174
0

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
  • 32,953
  • 42
  • 145
  • 236
  • 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 Oct 25 '10 at 14:08
0

You can use is_null() instead.

skynet
  • 9,898
  • 5
  • 43
  • 52
Brandon Frohbieter
  • 17,563
  • 3
  • 40
  • 62
0

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
  • 445,704
  • 82
  • 492
  • 529