-1

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

Josh K
  • 28,364
  • 20
  • 86
  • 132
  • 12
    What is wrong with isset() and empty()? – dscher Apr 07 '10 at 04:13
  • I thought I remembered reading about a different method on Coding Horror or another blog but couldn't remember it. I'm not saying something is wrong with isset() or empty(), just trying to poke the brain a bit. – Josh K Apr 07 '10 at 04:14
  • You have to be careful with `empty()` as it returns `true` for some special values such as the string `"0"`. – Asaph Apr 07 '10 at 04:17
  • there are other ways, although not really better, for example , `strlen()` – ghostdog74 Apr 07 '10 at 04:18
  • @Asaph - my bad for the previous comment, I read your post wrong. – dscher Apr 07 '10 at 04:19
  • @chad, I totally hit the snooze button and spaced out. Thanks for waking me up! – dscher Apr 07 '10 at 04:22
  • 1
    @Asaph Well yes, because it's, by PHP's definition, `empty`. That's because PHP deals a lot with strings, especially POST values, so `0` and `"0"` are regarded as equally empty. It's a rule you just have to learn. If you want more precise control, use `isset` and strictly compare to values **you** regard as empty. – deceze Apr 07 '10 at 04:23
  • 1
    @dscher: No worries. It happens to the best of us :) – Asaph Apr 07 '10 at 04:24

2 Answers2

4

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);
deceze
  • 510,633
  • 85
  • 743
  • 889
sam
  • 386
  • 1
  • 3
  • 10
2

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
  • 14,823
  • 5
  • 60
  • 78
  • 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 Apr 07 '10 at 09:23