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

前端 未结 3 1708
孤城傲影
孤城傲影 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:05

    You can compare two strings.

    "00001" === "1"  // false
    

    Remember == means equivalent === means equal

    My only guess as to why this is the case is because in the beginning PHP strived to be a type-less language before they went the route of becoming a loosely typed language.

    PHP was originally string processor that allowed for a little scripting inside of it. Since all inputs on the web are textual in nature it had to work hard given textual input to behave sanely when it came to dealing with numbers.

    I could be wrong about this but I don't believe the ability to explicitly cast data types entered the stage until PHP 4 with the introduction of the *val functions (like intval) etc. and I think the casting notation, like (int) came around after that.

    For the non comparison operations it was pretty easy because they all have a type associated with them (+ - / * all deal with numbers whereas . deals with strings) so a clear path to how things should be cast in those cases is apparent.

    But with equality or equivalence checks between variables then the only way to do that was to treat everything that looked like a number as a number because at the time the only way it could be gotten would be by externally would be as a string and there was no way to make it otherwise.

提交回复
热议问题