Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does empty("0") returns true in PHP?

Tags:

php

According to PHP documentation, the following expressions return true when calling empty($var)

  • "" (an empty string)
  • 0 (0 as an integer)
  • 0.0 (0 as a float)
  • "0" (0 as a string)
  • NULL
  • FALSE
  • array() (an empty array)
  • $var; (a variable declared, but without a value)

I've found how to "solve" the problem by using empty($var) && $var != 0 but why php developers did it?

I think it is ridiculous, suppose you have this code:

if (empty($_POST["X"])) {
    doSomething();
}

I think "0" is not empty, empty is when there is nothing!

Maybe it's better to use

if (isset($x) && x != "") {//for strings
    doSomething();
}
like image 471
user2961204 Avatar asked Aug 03 '14 01:08

user2961204


People also ask

Is 0 considered empty PHP?

Definition and UsageThis function returns false if the variable exists and is not empty, otherwise it returns true. The following values evaluates to empty: 0.

Is empty and null same in PHP?

is_null() The empty() function returns true if the value of a variable evaluates to false . This could mean the empty string, NULL , the integer 0 , or an array with no elements. On the other hand, is_null() will return true only if the variable has the value NULL .

Does PHP empty check empty 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.

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 !


1 Answers

empty roughly mirrors PHP's selection of FALSE-y values:

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer 0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • ...

As far as why PHP works this way, or why the empty function followed suit - well, that's Just The Way It Is.

Consider using strlen($x) (this is especially well-suited to sources like $_POST which are all string values) to determine if there is a non-empty string, including "0".

The final form I use would then be: isset($x) && strlen($x), with any additional processing applied knowing there was some post data.

like image 164
user2864740 Avatar answered Sep 19 '22 05:09

user2864740