32

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?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Run
  • 54,938
  • 169
  • 450
  • 748

12 Answers12

52

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jim
  • 18,673
  • 5
  • 49
  • 65
10

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.

Gordon
  • 312,688
  • 75
  • 539
  • 559
6

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
netcoder
  • 66,435
  • 19
  • 125
  • 142
6

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).

Enter image description here

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");
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
manish1706
  • 1,571
  • 24
  • 22
3

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)
Hamish
  • 22,860
  • 8
  • 53
  • 67
3

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');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user187291
  • 53,363
  • 19
  • 95
  • 127
  • The above is a little unclear on this: `is_int($var)` tests if `$var` is an integer *or* a string in integer format. So, e.g., `is_int("0")` will return true. To get the internal type of a variable, use `gettype($var)`. For example, `if(gettype($var) === "integer")`. – Chris Middleton Sep 16 '14 at 20:28
2

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

I suggest using a different function to match your specification.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
1
$var = '0';

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

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

};
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
1

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Stemar
  • 89
  • 1
  • 2
0

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Viper_Sb
  • 1,809
  • 14
  • 18
0

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 :)

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ferhat KOÇER
  • 3,890
  • 1
  • 26
  • 26
  • 1
    Please add a shot description to your answer, why and how these alternatives solve the initial problem. This helps the reader to understand the solution better. – user1438038 Jan 27 '17 at 14:26