Coding horrors: Apparently 2 == "2abc"
August 14, 2009 by
Christoff Truter
PHP
Coding Horrors
This one is for the PHP enthusiasts, most of you are hopefully probably aware
of this, but if you're not (and for people that adhere to other perhaps more
sane languages), the following condition will evaluate to true and output the text,
"How dodgy is this?"
if (2 == "2abc") {
echo "How dodgy is this?";
}
The reason for this can be found in the way that PHP handles conversion/casting
of its types. PHP will automatically convert the string ("2abc") to an integer to
allow comparison of the values (the joys of loosely typeness).
Which brings me to the next expression which gives us a clue of what's really happening.
$a = (int) "2abc";
echo $a;
The non numeric part of the variable will be stripped away, leaving us with an integer
value (if the string begins with a numeric value that is) - personally I believe this is
horrible functionality - a variable containing non numeric values must NOT be allowed to
be converted to an integer in this manner, conversion must fail.
Getting back to our if condition at the top, PHP introduced "identity" operators into their
codebase in version 4 (I believe), observe:
if (2 === "2abc") {
echo "How dodgy is this?";
}
This condition will evaluate to false and won't output anything, the reason being that
instead of converting the variables we're attempting to compare, it compares the inferred
types of each variable and only then the actual content of the variables.
In my opinion this is more credible (robust/safe) behaviour for an equality operator,
not to mention to all the other operators in PHP that work in the same fashion (which
might be too strict for a lot of PHP devs, something more familiar to strongly typed
languages like C#).
One could argue that since PHP is a loosely typed language, one should rather implement
some sane behaviour in the way PHP handles certain conversions and still allow PHP to convert
values automatically to make them compareable.
This is exactly how javascript (another loosely typed language) handles scenarios like this. The following condition will evaluate to false like expected.
if (2 == "2abc")
{
alert('True');
}
Unlike the identity operators in PHP, the following will evaluate to true, but since type conversion
seems to be more sane in javascript, it doesn't matter, they might not be equal in type, but they
are definitely equal in value.
if (2 == "2")
{
alert('True');
}
January 7, 2015 by Anonymous
@potherca looks like someone didn't read the full post ;)