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

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?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

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.

Solution 2

You cannot with empty. From the PHP Manual:

The following things are considered to be empty:

  • “” (an empty string)
  • 0 (0 as an integer)
  • “0” (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

You have to add an additional other check.

Solution 3

You can’t with only empty(). See the manual. You can do this though:

if ($var !== '0' && empty($var)) {
   echo "$var is empty and is not string '0'";
}

Basically, empty() does the same as:

if (!$var) ...

But it doesn’t trigger a PHP notice when the variable is not set.

Solution 4

PHP has different functions which can be used to test the value of a variable. Three useful functions for this are isset(), empty(), and is_null(). All these function return a boolean value. If these functions are not used in correct way they can cause unexpected results.

isset() and empty() are often viewed as functions that are opposite, however this is not always true. In this post I will explain the differences between these functions.

isset()

From PHP manual – isset():

isset — Determine if a variable is set and is not NULL

In other words, it returns true only when the variable is not null.
empty()

From PHP Manual – empty():

empty — Determine whether a variable is empty

In other words, it will return true if the variable is an empty string, false, array(), NULL, “0?, 0, and an unset variable.
is_null()

From PHP Manual – is_null():

is_null — Finds whether a variable is NULL

In other words, it returns true only when the variable is null. is_null() is opposite of isset(), except for one difference that isset() can be applied to unknown variables, but is_null() only to declared variables.

The table in picture is an easy reference for what these functions will return for different values. The blank spaces means the function returns bool (false).

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

Also I have made a custom function for checking all stuff:

function checkEmpty($var, $term = ""){
    if(isset($var) && trim($var) != "" && (!empty($var) || trim($var) == 0)){
        return true;
    }
    else{
        if($term != ""){
            return array("status" => "error", "desc" => "$term can not be empty");
        }
        else{
            return array("status" => "error", "desc" => "value can not be empty");
        }
    }
}

Solution 5

You can’t. From the manual

Returns FALSE if var has a non-empty and non-zero value.

The following things are considered to be empty:

  • “” (an empty string)
  • 0 (0 as an integer)
  • “0” (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • var $var; (a variable declared, but without a value in a class)

Solution 6

In both of your cases empty() will return true. Check the documentation.

I suggest using a different function to match your specification.

Solution 7

empty is by far the most confusing and useless function in the PHP repertoire. Don’t use it.

There are three separate things you want to know when checking a value.

  • the value exists (use isset)
  • the value has a specific type (use is_xxx)
  • the value has specific properties (use comparison operators, strpos or regular expressions).

(the last two can be combined into one with typecasts or ‘===’).

Examples:

if(isset($var) && is_string($var) && strlen($var) > 0)...
if(isset($var) && intval($var) > 0)...
if(isset($var) && $var === '0')...

This seems more verbose, but it shows clearly what you’re doing. For structural objects it often makes sense to have a shortcut getter, e.g.

 /// Get a string
 function s($ary, $key, $default = '') {
     if(!isset($ary[$key])) return $default;
     $s = trim($ary[$key]);
     return strlen($s) ? $s : $default;
 }
 /// Get a natural number
 function n($ary, $key, $default = 0) {
     $n = intval(s($ary, $key));
     return $n > 0 ? $n : $default;
 }

 $name = s($_POST, 'name');
 $age  = n($_POST, 'age');

Solution 8

$var = '0';

// Evaluates to true because $var is empty
if (empty($var) && $var !== '0') {
    echo '$var is empty or the string "0"';
}

Solution 9

I always add this 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 is_blank() which was added May 2011.

Solution 10

If you want skip an empty $filter and don’t skip $filter = ‘0’ and other values:

$filter = ''; // Or $filter = '0'; or $filter = '1';

// Trim the $filter

if(isset($filter) and ($filter != '' or $filter == '0')) {

    // $filter data

};

Solution 11

In this case, don’t use empty(). Use isset() in place of it. This will also allow 0 as an integer.

$var = '0';
if (!isset($var)) {
    print '$var is not set';
}

$var = 0;
if (!isset($var)) {
    print '$var is not set';
}

Neither should print anything.

Solution 12

You can not, because integer, string, float, and null do not matter for PHP.

Because it is cool 🙂

You must check characteristic features for your variable: is_numeric(), isset(), ===, strlen(), etc.

For example:

if (strlen(@$var)==0) {
    echo @$var . ' is empty';
}

or

if (@$var==="" || !isset($var)) {
    echo @$var . ' is empty';
}

or other examples 🙂

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply