Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

If ... comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.

Okay, I got it. It explains what is going on when '00001' == '1' returns TRUE.

The question is: Why PHP does so?
What is the reason for probing strings for being numeric, and then casting if so? Why can't we just compare two strings already?

I can fairly understand what casting is required if two operands has different types. But why it does "usual math" when both are strings?

like image 952
Your Common Sense Avatar asked Jun 02 '13 05:06

Your Common Sense


1 Answers

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.

like image 118
Orangepill Avatar answered Oct 12 '22 23:10

Orangepill