- There is no (technical) difference – nor is there in Java to my knowledge.
- In PHP, do not use either of these.
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:
- short-circuiting operators
- order of evaluation
- operator precedence
I just found that the PHP manual says:
"PHP checks each condition in order from left to right"
No,
- the PHP manual does not say that, it's a comment.
- PHP does not do that.
PHP evaluates the conditions from left to right, but it stops once the result is known:
expr1 && expr2
If expr1
evaluates to false
, 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
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
PHP checks each condition in order from left to right
Ergo: The same "best practice" can be applied
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).
null = $a
is assignment andnull != $a
is comparison, did you meannull == $a
?null = $a
won't work, and yes in assignments order of interpretation is significant - and it wouldn't work in Java either. Are we talking conditionals or assignment?