Is there a better way besides isset()
or empty()
to test for an empty variable?
views:
103answers:
2
+3
A:
It depends upon the context.
isset()
will ONLY return true when the value of the variable is not NULL
(and thereby the variable is at least defined).
empty()
will return true when the value of the variable is deemed to be an "empty" value, typically this means 0
, "0"
, NULL
, FALSE
, array()
(an empty array) and ""
(an empty string), anything else is not empty.
Some examples
FALSE == isset($foo);
TRUE == empty($foo);
$foo = NULL;
FALSE == isset($foo);
TRUE == empty($foo);
$foo = 0;
TRUE == isset($foo);
TRUE == empty($foo);
$foo = 1;
TRUE == isset($foo);
FALSE == empty($foo);
sam
2010-04-07 04:18:39
Good enough for me, thanks.
Josh K
2010-04-07 04:19:58
`array()`, i.e. an empty array is also `empty`!
deceze
2010-04-07 04:42:27
+1
A:
Keep an eye out for some of the strange == results you get with PHP though; you may need to use === to get the result you expect, e.g.
if (0 == '') {
echo "weird, huh?\n";
}
if (0 === '') {
echo "weird, huh?\n";
} else {
echo "that makes more sense\n";
}
Because 0 is false, and an empty string is false, 0 == '' is the same as FALSE == FALSE, which is true. Using === forces PHP to check types as well.
El Yobo
2010-04-07 05:03:34
Agreed, use var_dump() on your variable before apply conditional code checks and keep this grid-check in mind: http://www.deformedweb.co.uk/php_variable_tests.php
Cups
2010-04-07 09:23:43