PHP: what's an alternative to empty(), where string "0" is not treated as empty?

Viewed 45607

Possible Duplicate:
Fixing the PHP empty function

In PHP, empty() is a great shortcut because it allows you to check whether a variable is defined AND not empty at the same time.

What would you use when you don't want "0" (as a string) to be considered empty, but you still want false, null, 0 and "" treated as empty?

That is, I'm just wondering if you have your own shortcut for this:

if (isset($myvariable) && $myvariable != "") ;// do something
if (isset($othervar  ) && $othervar   != "") ;// do something
if (isset($anothervar) && $anothervar != "") ;// do something
// and so on, and so on

I don't think I can define a helper function for this, since the variable could be undefined (and therefore couldn't be passed as parameter).

7 Answers

This should do what you want:

function notempty($var) {
    return ($var==="0"||$var);
}

Edit: I guess tables only work in the preview, not in actual answer submissions. So please refer to the PHP type comparison tables for more info.

notempty("")       : false
notempty(null)     : false
notempty(undefined): false
notempty(array())  : false
notempty(false)    : false
notempty(true)     : true
notempty(1)        : true
notempty(0)        : false
notempty(-1)       : true
notempty("1")      : true
notempty("0")      : true
notempty("php")    : true

Basically, notempty() is the same as !empty() for all values except for "0", for which it returns true.


Edit: If you are using error_reporting(E_ALL), you will not be able to pass an undefined variable to custom functions by value. And as mercator points out, you should always use E_ALL to conform to best practices. This link (comment #11) he provides discusses why you shouldn't use any form of error suppression for performance and maintainability/debugging reasons.

See orlandu63's answer for how to have arguments passed to a custom function by reference.

function isempty(&$var) {
    return empty($var) || $var === '0';
}

The key is the & operator, which passes the variable by reference, creating it if it doesn't exist.

if(isset($var) && ($var === '0' || !empty($var)))
{
}
if ((isset($var) && $var === "0") || !empty($var))
{

}

This way you will enter the if-construct if the variable is set AND is "0", OR the variable is set AND not = null ("0",null,false)

The answer to this is that it isn't possible to shorten what I already have.

Suppressing notices or warnings is not something I want to have to do, so I will always need to check if empty() or isset() before checking the value, and you can't check if something is empty() or isset() within a function.

function Void($var)
{
    if (empty($var) === true)
    {
        if (($var === 0) || ($var === '0'))
        {
            return false;
        }

        return true;
    }

    return false;
}
Related