【问题标题】:php string comparasion to 0 integer returns true? [duplicate]php字符串与0整数比较返回true? [复制]
【发布时间】:2012-01-30 02:41:52
【问题描述】:

可能重复:
Why does PHP consider 0 to be equal to a string?

我有这段代码:

$o['group'] = "prueba";
if( $o['group'] == 0){
    die("test");
}

为什么要打印测试?一个字符串怎么可能等于零?

【问题讨论】:

  • 在 PHP 中,空字符串和字符串 "0" 都将通过相等运算符 (==) 为零。
  • @MichaelMior:以及任何其他无法转换为数字的字符串。

标签: php


【解决方案1】:

使用带有类型检查“===”的比较运算符。在此处查看示例 http://php.net/manual/en/language.operators.comparison.php 并解释为什么 non-numerical 字符串与零相比总是返回 true

【讨论】:

    【解决方案2】:

    如果您希望它与字符串完全匹配,请尝试使用完全相同的三个等号,例如
    if( $o['group'] === 0){
    将字符串与整数 0 进行比较时,== 将始终评估为 true

    'a string' == 0 也计算为 true,因为任何字符串在与整数比较时都会转换为整数。如果 PHP 无法正确转换字符串,则将其评估为 0。因此 0 等于 0,即为真。

    来自here

    【讨论】:

    • 还是错了。 '0.1e2' == 0 是假的,尽管 (int) '0.1e2' === 0 是真的。字符串内容决定了字符串转换为哪种数据类型(intfloat)。
    • 是的,这仍然是错误的。仅在 $o['group'] == '0' 时有效
    猜你喜欢
    • 2012-04-12
    • 2012-12-24
    • 1970-01-01
    • 2013-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    相关资源
    最近更新 更多