gpt4 book ai didi

php - 为什么 empty ("0") 在 PHP 中返回 true?

转载 作者:可可西里 更新时间:2023-11-01 12:34:12 26 4
gpt4 key购买 nike

根据 PHP 文档,以下表达式在调用 empty($var) 时返回 true

  • ""(空字符串)
  • 0(0 为整数)
  • 0.0(0 作为 float )
  • “0”(0 作为字符串)
  • 错误
  • array()(空数组)
  • $变量; (声明的变量,但没有值)

我已经找到了如何使用 empty($var) && $var != 0 来“解决”这个问题,但是为什么 php 开发人员要这样做呢?

我认为这很荒谬,假设你有这段代码:

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

我觉得"0"不是空的,什么都没有的时候是空的!

也许用起来更好

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

最佳答案

大致镜像 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
  • ...

至于 为什么 PHP 以这种方式工作,或者 为什么 空函数采用这种方式 - 好吧,这就是它的方式。

考虑使用 strlen($x)(这特别适合像 $_POST 这样全是字符串值的来源)来确定是否有非空字符串,包括“0”。

我使用的最终形式将是:isset($x) && strlen($x),在知道有一些 post 数据的情况下应用任何额外的处理。

关于php - 为什么 empty ("0") 在 PHP 中返回 true?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25100890/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com