Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 428
null Avatar asked Jan 03 '09 22:01

null


People also ask

What is empty function in PHP?

PHP empty() Function The empty() function checks whether a variable is empty or not. This function returns false if the variable exists and is not empty, otherwise it returns true.

Is 0 considered empty PHP?

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

Should I use empty PHP?

You should use the empty() construct when you are not sure if the variable even exists. If the variable is expected to be set, use if ($var) instead. empty() is the equivalent of !

Is empty PHP string?

We can use empty() function to check whether a string is empty or not. The function is used to check whether the string is empty or not. It will return true if the string is empty. Parameter: Variable to check whether it is empty or not.


2 Answers

This didn't work for me.

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

I used instead:

if (empty($variable) && strlen($variable) == 0) {   // Do something } 
like image 79
Marv3lz Avatar answered Sep 20 '22 20:09

Marv3lz


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.

like image 33
Bill Karwin Avatar answered Sep 21 '22 20:09

Bill Karwin