'0' as a string with empty() in PHP

laukok picture laukok · Nov 9, 2010 · Viewed 54.7k times · Source

I want a 0 to be considered as an integer and a '0' to be considered as a string, but empty() considers the '0' as a string in the example below,

$var = '0';

// Evaluates to true because $var is empty
if (empty($var)) {
    echo '$var is empty';
}

How can I 'make' empty() to take '0's as strings?

Answer

Jimithus picture Jimithus · Nov 9, 2010

You cannot make empty() take it. That is how it was designed. Instead you can write an and statement to test:

if (empty($var) && $var !== '0') {
    echo $var . ' is empty';
}

You could use isset, unless of course, you want it to turn away the other empties that empty checks for.