php: check if variable contains a value

2025-07-04 09:23:39 IN1 , 2025-07-04 14:40:38 IN1


The value 0 is also considered empty - although there is definitely a value here.

If you want to prevent this, you must also query for false === is_numeric - this excludes 0.

So here we do not check for emptiness, but for value
which makes false === hasValue() equivalent in the same meaning to true === empty(),
but considers 0 value and boolean values as well.

Everything is a value, except null and empty string.

function hasValue()

/**
 * @param mixed $mValue
 * @return bool
 */
function hasValue(mixed $mValue): bool
{
    return ((false === (true === empty($mValue) && false === is_numeric($mValue))) || is_bool($mValue));
}

Test

$aData = array(
    new StdClass(),
    '',
    0,
    '0',
    'test',
    123,
    null,
    false,
    true
);

// iterate and test
foreach ($aData as $mValue)
{
    echo str_repeat('-', 80) . "\n";
    echo var_export($mValue, true) . "\n";
    echo 'hasValue: ';
    var_dump(
        hasValue($mValue)
    );
    echo "\n";
}

Result

--------------------------------------------------------------------------------
(object) array(
)
hasValue: bool(true)

--------------------------------------------------------------------------------
''
hasValue: bool(false)

--------------------------------------------------------------------------------
0
hasValue: bool(true)

--------------------------------------------------------------------------------
'0'
hasValue: bool(true)

--------------------------------------------------------------------------------
'test'
hasValue: bool(true)

--------------------------------------------------------------------------------
123
hasValue: bool(true)

--------------------------------------------------------------------------------
NULL
hasValue: bool(false)

--------------------------------------------------------------------------------
false
hasValue: bool(true)

--------------------------------------------------------------------------------
true
hasValue: bool(true)
This website uses Cookies to provide you with the best possible service. Please see our Privacy Policy for more information. Click the check box below to accept cookies. Then confirm with a click on "Save".