I was wondering what's the difference the two cases below, and which one is recommended?
$val = 0;
if (!$val) {
//True
}
if (empty($val) {
//It's also True
}
I was wondering what's the difference the two cases below, and which one is recommended?
$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 anE_NOTICE
, whereasempty($x)
does not.Let see:
empty
documentation:Booleans documentation:
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).If you use empty and the variable was never set/created, no warning/error will be thrown.