First off, sorry if this is answered somewhere else. I did a brief search, but wasn’t sure how to ask in search terms.
I’m looking at some code and came across lot’s of statements like this:
if ( ($a != empty_or_null_or_notDefined && $a == 5 )
Is this the same as just saying:
if ( $a == 5 )
?
(language is PHP.)
1
At a purely logical level, presuming &
is the local and operator, then $a
being 5
precludes it from being null
.
That said, in some languages, and short circuits (that is, if one operand fails, it does not check the others, as the whole clause is known to fail when one does). In this case, this could be a move for efficiency, although it’s highly unlikely equality is an expensive enough operation to make this worthwhile (especially as PHP doesn’t offer operator overloading).
As it’s PHP, a single ampersand is a bitwise and
operation, not a logical one, as such, it will not be lazy. Your topic has one ampersand, while the question itself has two, I think the latter is more likely to be the real option (as what is happening is a logical check), but you should clarify.
3
This code is necessary to avoid errors. If you try to access an undefined object, you get a fatal error.
Checking whether this object is not undefined before checking the value allows you to work around this error.
If the first check doesn’t pass (is it undefined?), it won’t check the value, thus will not throw an error.
3
Nice question.
Logic A # if ( ($a != empty_or_null_or_notDefined && $a == 5 )
Logic B # if ( $a == 5 )
Logic B is better than Logic A. (Regarding Algorithm complexity)
If your purpose is only Logic B, then you don’t need Logic A.
NULL is critical. It can be stated as Undefined, Empty, etc.
Better to escape NULL comparison, because it is hard to debug.
I support @Florian Margaine’s answer, absolutely, Every code is necessary to avoid errors. If you try to access an undefined object, you get a fatal error. Checking whether this object is not undefined before checking the value allows you to work around this error.
And if comparison to NULL is necessary to you, then please have a look at the following resource
https://stackoverflow.com/questions/381265/better-way-to-check-variable-for-null-or-empty-string