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

1

6 Answers 6

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.

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

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.

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.

1
  • 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. Commented Oct 25, 2010 at 14:08
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:

0

You can use is_null() instead.

1
  • Not what he was asking, this is about operand order.
    – fredley
    Commented Oct 25, 2010 at 13:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.