in php, why empty(“0”) returns true?

百般思念 提交于 2019-12-09 02:49:09

问题


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, suppouse 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();
}

回答1:


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.



来源:https://stackoverflow.com/questions/25100890/in-php-why-empty0-returns-true

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!