I see a lot of people using a variety of different methods to check whether of a variable is empty, there really seems to be no consensus. I've heard that if($foo)
is exactly the same as if(!empty($foo))
or if($foo != "")
. Is this true?
I realize it's a really simple question, but I'd really like to know. Are there any differences? Which method should I use?
if($foo != "")
is equivalent to if($foo)
most of the time, but not always.
To see where the differences are, consider the comparison operator behavior along with the conversion to string rules for the first case, and the conversion to boolean rules for the second case.
What I found out is that:
$foo === array()
, the if($foo != "")
test will succeed (arrays are "greater than" strings), but the if($foo)
test will fail (empty arrays convert to boolean false
)$foo === "0"
(a string), the if($foo != "")
test will again succeed (obviously), but the if($foo)
test will fail (the string "0"
converts to boolean false
)$foo
is a SimpleXML object created from an empty tag, the if($foo != "")
test will again succeed (objects are "greater than" strings), but the if($foo)
test will fail (such objects convert to boolean false
)See the differences in action.
The preferred method to test is if(!empty($foo))
, which is not exactly equal to the above in that:
if($foo != "")
(which IMHO is simply horrible).E_NOTICE
if $foo
is not present in the current scope, which is its main advantage over if($foo)
.There's a caveat here though: if $foo === '0'
(a string of length 1) then empty($foo)
will return true
, which usually is (but may not always be) what you want. This is also the case with if($foo)
though.
Finally, an exception to the above must be made when there is a specific type of value you want to test for. As an example, strpos
might return 0
and also might return false
. Both of these values will fail the if(strpos(...))
test, but they have totally different meanings. In these cases, a test with the identical operator is in order: if(strpos() === false)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With