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

前端 未结 1 1856
陌清茗
陌清茗 2021-01-08 00:02

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

  • \"\" (an empty string)
  • 0 (0 as an integer)
相关标签:
1条回答
  • 2021-01-08 00:50

    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.

    0 讨论(0)
提交回复
热议问题