In php, why does empty ("0") return true?

According to php documentation, following expressions return true when called empty($var)

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

I found how to "solve" the problem using empty($var) && $var != 0

, but why did the php developers do this? i think it's funny, suppouse you have this code:

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

      

I think "0"

not empty, empty when there is nothing !!! it might be better to use

if (isset($x) && x != "") {//for strings
    doSomething();
}

      

+3


source to share


1 answer


empty

coarse mirror PHP selection of FALSE-y values :

When converted to boolean, the following values ​​are considered FALSE:

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

To what extent PHP works this way or why the empty function followed suit - well, it's just the way it is.



Consider using strlen($x)

(this works especially well for sources such as $_POST

which are all string values) to determine if a non-empty string exists, including "0".

The last form I use would then be:, isset($x) && strlen($x)

with any additional processing used knowing there is some data to post.

+3


source







All Articles