开发者

Empty PHP variables

Is there a better way besides isset() or e开发者_StackOverflow社区mpty() to test for an empty variable?


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);


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜