Very illogical php value comparisons

前端 未结 8 2039
慢半拍i
慢半拍i 2021-01-11 12:58

I stumbled upon a very strange bit of PHP code. Could someone explain why this is happening? *****BONUS POINTS***** if you can tell my why this is useful.



        
8条回答
  •  北海茫月
    2021-01-11 13:19

    I don't see how ('a'==0) is helpful

    $var = '123abc';
    
    if (123 == $var)
    {
        echo 'Whoda thunk it?';
    }
    

    It comes down to PHP's implicit conversion rules.

    I'm failing at thinking of a practical example, but that's the basic reason why you're seeing that behavior.

    Expansion:

    In your example, 'a' is converted to 0 (zero), for the comparison. Imagine that for the purpose of the comparison, it's equivalent to '0a'. (That's the numeral zero, not the letter 'o.')

    Further expansion:

    I thought there was a good example use case for this in the manual, but I failed to find it. What I did come across should help shed some light on this "illogical" situation.

    PHP is first and foremost a Web language, not a general-purpose scripting language. Since the Web is not typed and everything is a string, I had to do things slightly differently early on to make PHP do what people expected. Specifically, "123"==123 needs to be true in order to not have to type cast every single numeric user input.

    http://bugs.php.net/bug.php?id=48012

    That doesn't exactly answer the question, but it points in the general direction.

提交回复
热议问题