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
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
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
.
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.
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.
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.
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
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:
You can use is_null()
instead.