Why does (“00e0” == “00e1”) evaluate as true?

后端 未结 1 1032
半阙折子戏
半阙折子戏 2021-01-04 20:55

In PHP, why do the first two of the following statement evaluate true?



        
相关标签:
1条回答
  • 2021-01-04 21:11

    It's because the strings that are valid floating point values are being interpreted as such.

    For example, 00e0 is equivalent to 0 x 100 and 00e9 is equivalent to 0 x 109, both of which are zero, and hence equal to each other.

    However, since 00ea is not a valid floating point number, it is being treated differently.

    You can see a similar effect with:

    echo "01e2" - "01e1";
    

    which outputs 90 because it's the same as 1 x 102 - 1 x 101, or 100 - 10.

    This is supported by the PHP doco (my italics):

    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.

    That paragraph links to another page which explains the rules behind conversion, should it happen:

    If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.

    If you want to avoid this behaviour, there's a note in that first link which states you should use === instead:

    The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.

    0 讨论(0)
提交回复
热议问题