null
null

Reputation: 7594

Fixing the PHP empty function

PHP has the habit of evaluating (int)0 and (string)"0" as empty when using the empty() function. This can have unintended results if you expect numerical or string values of 0. How can I "fix" it to only return true to empty objects, arrays, strings, etc?

Upvotes: 34

Views: 18523

Answers (13)

thomasrutter
thomasrutter

Reputation: 117403

If you want an equivalent to empty($var) which returns false when var is the string "0", you can use:

if (($var ?? 0) != '')

The reason this works is:

  • $var ?? 0 is a shortcut for the ternery isset($var) ? $var : 0. That is, if the variable on the left doesn't exist it takes the value on the right, without issuing a warning or notice, as with isset() or empty().

  • <value> != '' does an implicit cast of the empty string when the left value isn't a string. This returns false for any false-like value of <value> such as null, false or (numeric) 0. However, for the string "0", this will return true, since no cast will be performed and "0" != "" is true.

Upvotes: 0

Nere
Nere

Reputation: 4097

I used ord function to check either the value passed was empty or not.

/*
* SPACE is not empty - Please do trim before using this function for your own purpose
*  var_dump(is_having_value(0));        // true
   var_dump(is_having_value(0000));     // true
   var_dump(is_having_value("    0"));  // true
   var_dump(is_having_value(""));       // false
   var_dump(is_having_value("  "));     // true
   var_dump(is_having_value('\t'));     // true
   var_dump(is_having_value(''));       // false
   var_dump(is_having_value('o'));      // true
   var_dump(is_having_value('O'));      // true
   var_dump(is_having_value('0'));      //true
   var_dump(is_having_value(null));     //false
   var_dump(is_having_value());         //false
*/
function is_having_value($val = null) {
    if (is_array($val) || is_object($val)):
        $logic_empty = empty($val);
        return !$logic_empty;
    else:
        $ascii = ord($val);
        if ($ascii == 48 || $ascii = 0 || $ascii == 32):
            return true;
        else:
            $logic_empty = empty($val);
            return !$logic_empty;
        endif;
    endif;
}

Upvotes: 0

dewaz
dewaz

Reputation: 147

I use this to detect emptiness:

''  --> true
'0' --> false
0   --> false

the function:

function is_empty_or_zero($str) {
 return (is_null($str) || ($str === ''));
}

Upvotes: 1

Marv3lz
Marv3lz

Reputation: 464

This didn't work for me.

if (empty($variable) && '0' != $variable) {
  // Do something
}

I used instead:

if (empty($variable) && strlen($variable) == 0) {
  // Do something
}

Upvotes: 44

Sergey Onishchenko
Sergey Onishchenko

Reputation: 7861

if ( is_int($val) || !empty($val) ) {;}

Upvotes: 0

Stemar
Stemar

Reputation: 89

I always add 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 http://www.php.net/manual/en/function.empty.php#103756 which was added May 2011.

Upvotes: 7

staticsan
staticsan

Reputation: 30555

You're trying to use empty() for something it's not intended for. Personally, I think it's behaviour comes from an older programming paradigm in PHP and it could probably be retired.

Instead, make your checks more explicit. Rather than checking if the value is not useful, check that it is. For example, if you want an array, check it's an array (is_array()) rather than checking whether it's a string.

Also, you can rely on the fact that all $_POST and $_GET variables are strings, so you can make comparisons to "", or check that strlen() == 0.

Upvotes: 1

Nikola Stjelja
Nikola Stjelja

Reputation: 3687

The most effective solution for this problem is to test if the variable is false e.g.


if (!$variable_name) {echo $variable_name;}

It doesn't matter if the variable is empty or null, it all equals to false when put in a if conditional.

Upvotes: -3

too much php
too much php

Reputation: 91038

"0" is always considered false (or empty) in PHP, and it does make alot of sense (not that I'll argue that here). If you want to have zero evaluate to true as well, use strlen($value).

Upvotes: 8

Noah Goodrich
Noah Goodrich

Reputation: 25263

Generally speaking you want to use the triple equals operator to determine when a value truly is null or false. This is more specific and the results ALWAYS return exactly as expected.

Creating a separate function to do something that you can do in a single line of code but using a different operator seems to be overly complicated and adds additional obfuscation.

Additionally, many programmers tend to use 0 or an empty string to denote a non-existent value but it is more correct (and I feel a better practice) to use a null value to denote any value (regardless of type) that is truly non-existent.

Upvotes: 4

Bill Karwin
Bill Karwin

Reputation: 562651

I seldom use empty() for the reason you describe. It confuses legitimate values with emptiness. Maybe it's because I do a lot of work in SQL, but I prefer to use NULL to denote the absence of a value.

PHP has a function is_null() which tests for a variable or expression being NULL.

$foo = 0;
if (is_null($foo)) print "integer 0 is null!\n"; 
else print "integer 0 foo is not null!\n";

$foo = "0";
if (is_null($foo)) print "string '0' is null!\n"; 
else print "string '0' is not null!\n";

$foo = "";
if (is_null($foo)) print "string '' is null!\n"; 
else print "string '' is not null!\n";

$foo = false;
if (is_null($foo)) print "boolean false is null!\n"; 
else print "boolean false is not null!\n";

You can also use the exactly equals operator === to do a similar test:

if ($foo === null) print "foo is null!\n";

This is true if $foo is NULL, but not if it's false, zero, "", etc.

Upvotes: 19

dkretz
dkretz

Reputation: 37655

"Fixing" is one point of view. Another would be to assume it's not "broken", and learn to work with it the way it was intentionally designed.

Given the problem as you describe it, the best thing would be to tighten up your code so the variable can't be put into an indeterminate type state. Otherwise, you'll want to test for datatype using gettype().

Upvotes: 4

null
null

Reputation: 7594

I created an IsEmpty() a terse quick function.

function IsEmpty($mData) {
    return is_int($mData) ? false : 
        is_string($mData) ? $mData=="" : 
        empty($mData);
}

Upvotes: 0

Related Questions