PHP: if (!$val) VS if (empty($val)). Is there any difference?
10,387
Solution 1
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.
Solution 2
If you use empty and the variable was never set/created, no warning/error will be thrown.
Solution 3
Let see:
The following things are considered to be
empty
:
""
(an empty string)0
(0
as an integer)0.0
(0
as a float)"0"
(0
as a string)NULL
FALSE
array()
(an empty array)var $var;
(a variable declared, but without a value in a class)
When converting to boolean, the following values are considered
FALSE
:
- the boolean
FALSE
itself- 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)SimpleXML
objects 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).
Related videos on Youtube
Author by
Bachx
Updated on June 04, 2022Comments
-
Bachx almost 2 years
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 }
-
rockerest over 12 years+1. Also note that this is the same as
!= [boolean result of evaluating $val]
, so the last column of the first table is mostly what you should be looking at. -
Jason McCreary over 12 yearsSo what's the conclusion? From the list, boolean seems like the more robust check...
-
Bachx over 12 yearsThanks, that's what I needed to know. So I guess empty($x) is the safer approach. I assume the difference is negligible performance wise right?
-
xdazz over 12 yearsPlease note that when using empty() on inaccessible object properties, the __isset overloading method will be called, if declared.
-
Mark Amery almost 9 yearsThis is incorrect. A quick test at the PHP shell reveals that
empty
handles emptySimpleXMLElement
instances just like!
does; it's simply an error in theempty
documentation that they aren't mentioned there. -
leonbloy about 5 yearsGotta love the duplication of doc.