Why PHP casts two numerical strings to numbers before [loosely] comparing them?

前端 未结 3 1716
孤城傲影
孤城傲影 2021-01-17 12:51

I browsed through several similar questions, but they all only state the fact:

If ... comparison involves numerical strings, then each string is conve

3条回答
  •  爱一瞬间的悲伤
    2021-01-17 13:03

    Ah, finally I got it. It was quite stupid of me.

    Comparison involves not only "is equal" but also "less than" and "greater than". And for the latter two it is obviously critical to cast numerical operands before comparison, because numbers often being represented in PHP as strings, and 11 have to be greater than 9 even if both stored in strings.

    So, as compare_function() does all the comparisons at once, returns either 1, 0, -1 to tell if first operand is bigger, equal or less than second respectively - well, it's fairly explains, why operands being cast.

提交回复
热议问题