views:

103

answers:

2

Is there a better way besides isset() or empty() to test for an empty variable?

+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
Good enough for me, thanks.
Josh K
`array()`, i.e. an empty array is also `empty`!
deceze
+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
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