I am used to Java and therefore always think conditions are interpreted from left to right, i.e. there is a vital difference in null != $obj
and $obj != null
Now this seems not to be the case with PHP.
Can I do something wrong in PHP when I always start with null
on the left-hand side? Can I keep my behaviour from Java or do I need to train myself to do something else when dealing with PHP conditions?
Best Answer
I recommend you always use the strict comparison operators
===
and!==
if possible. You will know when you actually need loose comparison operators.Misunderstandings
I believe you may be confused about a couple of things:
No,
PHP evaluates the conditions from left to right, but it stops once the result is known:
If
expr1
evaluates tofalse
,expr2
will not be evaluated. This is called short-circuiting and it does not seem to be very well-documented – I couldn't find any other official note on the matter except for the comment in Example #1. It is a well-known feature, though.Fallacies
Ergo: nothing – non sequitur. The conclusion does not follow from the premise. Using
constant == $variable
or$variable == constant
is not connected to either of short-circuiting, order of evaluation or operator precedence.Undefined behavior
Both operands of
!=
are always evaluated. In the case of PHP, the evaluation order (which is irrelevant here) is actually unspecified (as in absent from the documentation).