The difference between the naked test and the comparison with the empty string
if($foo != "") in most cases equivalent to if($foo) , but not always.
To find out where the differences are, consider the behavior of the comparison operator and conversion to string rules for the first case and conversion to logical rules for the second case.
I learned that:
- if
$foo === array() , the if($foo != "") test will succeed (arrays are greater than "), but the if($foo) test will fail (empty arrays are converted to boolean false ) - if
$foo === "0" (string), if($foo != "") test will succeed again (obviously), but if($foo) test will fail (string "0" converted to boolean false ) - If
$foo is a SimpleXML object created from an empty tag, the if($foo != "") Test will succeed again (more than objects), but the if($foo) test will fail (such objects are converted to boolean false )
See the differences in action .
Best way to test
the preferred testing method is if(!empty($foo)) , which does not quite match the above:
- It does not suffer from inconsistencies
if($foo != "") (Which IMHO is just awful). - It will not generate
E_NOTICE if $foo not in the current area, which is its main advantage over if($foo) .
There is a caveat: if $foo === '0' (string of length 1), then empty($foo) will return true , which usually (but may not always) be what you want. This also applies to if($foo) though.
Sometimes you need to test with an identical statement
Finally, an exception to the above should be made when there is a certain type of value that you want to check. As an example, strpos may return 0 , and may also return false . Both of these values will fail the test if(strpos(...)) , but they have completely different values. In these cases, a test with an identical operator is performed as follows: if(strpos() === false) .
Jon
source share