Type casting and Comparison with Loose Operator “==”

前端 未结 7 2356
暖寄归人
暖寄归人 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:17

    You made an error with your post, the correct output is this:

    bool(true)
    bool(true)
    int(0)
    string(6) "string"
    

    What happens is this:

    1. Because you cast the variable to an integer, and you compare it to an integer with a loose comparison ==, PHP will first implicitely cast the string to an integer, a more explicit but 100% equivalent form would be: if((int)$var1 == (int) $var1)
    2. See 1), the same thing applies here
    3. It prints int(0), as it should, because it fails to parse the number, it will return 0 instead.
    4. Prints string(6) "string" - as expected

提交回复
热议问题