I was wondering what's the difference the two cases below, and which one is recommend开发者_C百科ed?
$val = 0;
if (!$val) {
//True
}
if (empty($val) {
//It's also True
}
Have a look at the PHP type comparison table.
If you check the table, you'll notice that for all cases, empty($x) is the same as !$x. So it comes down to handling uninitialised variables. !$x creates an E_NOTICE, whereas empty($x) does not.
If you use empty and the variable was never set/created, no warning/error will be thrown.
Let see:
empty documentation:
The following things are considered to be
empty:
""(an empty string)0(0as an integer)0.0(0as a float)"0"(0as a string)NULLFALSEarray()(an empty array)var $var;(a variable declared, but without a value in a class)
Booleans documentation:
When converting to boolean, the following values are considered
FALSE:
- the boolean
FALSEitself- the integer
0(zero)- the float
0.0(zero)- the empty string, and the string
"0"- an array with zero elements
- an object with zero member variables (PHP 4 only)
- the special type
NULL(including unset variables)SimpleXMLobjects created from empty tags
It seems the only difference (regarding the resulting value) is how a SimpleXML instance is handled. Everything else seems to give the same result (if you invert the boolean cast of course).
加载中,请稍侯......
精彩评论