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
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
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.
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.
It doesn't really matter as long you don't forget to write ==
instead of =
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:
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.
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