Type casting and Comparison with Loose Operator “==”

前端 未结 7 2347
暖寄归人
暖寄归人 2020-12-10 16:58

I have a problem baffling me terribly. I noticed this before but didn\'t give it any heed until today. I was trying to write my own check for integer strings. I know of

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-10 17:02

    It's not a bug, it's a feature. Any string can be casted to an integer, but the cast will return 0 if the string doesn't start with an integer value. Also, when comparing an integer and a string, the string is casted to an integer and then the check is done against the two integers. Because of that rule, about just any random string is "equal" to zero. (To bypass this behavior, you should use strcmp, as it performs an explicit string comparison by casting anything passed to a string.)

    To make sure I'm dealing with an integer, I would use is_numeric first, then convert the string to an int, and verify that the stringified int corresponds to the input value.

    if (is_numeric($value) && strcmp((int)$value, $value) == 0)
    {
        // $value is an integer value represented as a string
    }
    

提交回复
热议问题