duanbu1998 2013-04-01 20:39
浏览 44
已采纳

if语句在PHP中没有得到尊重

if ($fromcat == "true" || $fromcat == 1){

    error_log("binding to CAT " . $cat . " because pfc was " . $fromcat);   

} else {

    error_log("binding to ROOM " . $room . " because pfc was " . $fromcat); 

}

please have a look at the code above.

I think everybody agree that if $fromcat is 0 there's no way I could get a "binding to CAT (...)" message in my console.

And yet, here it is:

[01-Apr-2013 22:34:50] binding to CAT single because pfc was 0

How is that even possible? You can't display the word CAT and the number 0 at the same time! Is PHP drunk?

  • 写回答

2条回答 默认 最新

  • dongshou1856 2013-04-01 20:41
    关注

    Use the identical (===) comparison operator.

    if ($fromcat === "true" || $fromcat === 1) {
    
        error_log("binding to CAT " . $cat . " because pfc was " . $fromcat);   
    
    } else {
    
        error_log("binding to ROOM " . $room . " because pfc was " . $fromcat); 
    
    }
    

    You are attempting to compare $fromcat to the string "true". If you wanted to compare it to the boolean true, you would use $fromcat == true. Otherwise:

    If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

    Documentation

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画