Fixing the PHP empty function

This didn't work for me.

if (empty($variable) && '0' != $variable) {
  // Do something
}

I used instead:

if (empty($variable) && strlen($variable) == 0) {
  // Do something
}

"0" is always considered false (or empty) in PHP, and it does make alot of sense (not that I'll argue that here). If you want to have zero evaluate to true as well, use strlen($value).


I always add to my codebase

function is_blank($value) {
    return empty($value) && !is_numeric($value);
}

and use it instead of empty(). It solves the issue of keeping zeros (int, float or string) as non-empty.

See http://www.php.net/manual/en/function.empty.php#103756 which was added May 2011.


I seldom use empty() for the reason you describe. It confuses legitimate values with emptiness. Maybe it's because I do a lot of work in SQL, but I prefer to use NULL to denote the absence of a value.

PHP has a function is_null() which tests for a variable or expression being NULL.

$foo = 0;
if (is_null($foo)) print "integer 0 is null!\n"; 
else print "integer 0 foo is not null!\n";

$foo = "0";
if (is_null($foo)) print "string '0' is null!\n"; 
else print "string '0' is not null!\n";

$foo = "";
if (is_null($foo)) print "string '' is null!\n"; 
else print "string '' is not null!\n";

$foo = false;
if (is_null($foo)) print "boolean false is null!\n"; 
else print "boolean false is not null!\n";

You can also use the exactly equals operator === to do a similar test:

if ($foo === null) print "foo is null!\n";

This is true if $foo is NULL, but not if it's false, zero, "", etc.