Run
Run

Reputation: 57176

'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?

Upvotes: 33

Views: 71143

Answers (12)

Ivan Procopet
Ivan Procopet

Reputation: 11

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

};

Upvotes: 1

manish1706
manish1706

Reputation: 1599

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");
        }
    }
}

Upvotes: 7

Ferhat KOÇER
Ferhat KOÇER

Reputation: 4065

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

Upvotes: 0

Stemar
Stemar

Reputation: 89

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.

Upvotes: 1

user187291
user187291

Reputation: 53940

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');

Upvotes: 3

netcoder
netcoder

Reputation: 67695

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.

Upvotes: 6

Jason McCreary
Jason McCreary

Reputation: 72971

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

I suggest using a different function to match your specification.

Upvotes: 2

Viper_Sb
Viper_Sb

Reputation: 1817

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.

Upvotes: 0

Jim
Jim

Reputation: 18853

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.

Upvotes: 53

2371
2371

Reputation: 947

$var = '0';

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

Upvotes: 1

Hamish
Hamish

Reputation: 23316

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)

Upvotes: 3

Gordon
Gordon

Reputation: 316969

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.

Upvotes: 10

Related Questions