duanbu1998 2013-04-01 20:39 采纳率: 0%
浏览 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条)

报告相同问题?