phpvariablesnull-test

Empty PHP variables


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


Solution

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