dongmen5867
2013-10-31 09:00
浏览 28
已采纳

PHP中奇怪的逻辑行为 - 这是正常的吗?

Can anyone figure out why this might happen in PHP (am using v5.4):

$value = 0;
$existing_value = "Unknown";

if ($value == $existing_value) {
    echo "$value == $existing_value";
} else {
    echo "$value != $existing_value";
}

This outputs as 0 == Unknown

Interestingly, $value = "0" (i.e. set as a string), evaluates to be false

Is this a known behaviour? Have I missed something in the documentation on this? Debugging this was driving me crazy earlier today!

Thanks for your help in advance...

图片转代码服务由CSDN问答提供 功能建议

任何人都可以找出PHP中可能发生的原因(使用v5.4):

  $ value = 0; 
 $ existing_value =“Unknown”; 
 
if($ value == $ existing_value){
 echo“$  value == $ existing_value“; 
} else {
 echo”$ value!= $ existing_value“; 
} 
   
 
 

输出为 0 ==未知

有趣的是, $ value =“0”(即设置为字符串),评估为假

这是一种已知行为吗? 我在文档中遗漏了什么吗? 调试这个让我今天早些时候变得疯狂了!

感谢您的帮助...

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

3条回答 默认 最新

  • duanpacan2583 2013-10-31 09:04
    已采纳

    This is caused by the automatic type casting, PHP uses.

    When comparing an int value with a string using just ==, the string will be casted to an int, which in your case results in a 0 and hence a true evaluation.

    See the respective PHP documentation for more information.

    To circumvent this, you could use === instead of ==. The former includes a type check, which will make your condition evaluate to false:

    $value = 0;
    $existing_value = "Unknown";
    
    if ($value === $existing_value) {
        echo "$value === $existing_value";
    } else {
        echo "$value !== $existing_value";
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • douqiao1997 2013-10-31 09:04

    When you compare a number with a string in PHP, as you do here, the string is converted to a number. Since the string "Unknown" is not numeric, it's converted to the number 0.

    If you check for equality with the === operator, it won't perform type conversion and it'll evaluate as false.

    http://php.net/manual/en/language.operators.comparison.php

    评论
    解决 无用
    打赏 举报
  • dtx6087 2013-10-31 09:04

    You should have a look at the comparison tables in PHP Especially the loose comparison (using ==) section as compared to the strict comparison (using ===) section.

    enter image description here

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题