在php中,为什么empty("0")返回true? [英] in php, why empty("0") returns true?

查看:153
本文介绍了在php中,为什么empty("0")返回true?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据php文档,调用empty($var)

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

  • "(一个空字符串)
  • 0(0为整数)
  • 0.0(浮点数为0)
  • "0"(0作为字符串)
  • NULL
  • array()(一个空数组)
  • $ 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)

我已经找到了如何通过使用empty($var) && $var != 0解决"问题的方法,但是为什么php开发人员做到了呢? 我认为这很荒谬,请支持以下代码:

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

我认为"0"不为空,什么也没有时为空!!! 也许最好使用

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

推荐答案

empty 大致镜像

转换为布尔值时,以下值为FALSE:

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

  • 布尔值FALSE本身
  • 整数0(零)
  • 浮点数0.0(零)
  • 空字符串和字符串"0"
  • 具有零个元素的数组
  • ...
  • 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.

考虑使用strlen($x)(这尤其适合$_POST等都是字符串值的源)来确定是否存在非空字符串,包括"0".

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".

然后,我使用的最终形式将是:isset($x) && strlen($x),在知道有一些个帖子数据的情况下,进行了任何其他处理.

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

这篇关于在php中,为什么empty("0")返回true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆