Markus Malkusch's weblog 

The weakly typed String Comparison in PHP

by Markus Malkusch


Posted on Thursday May 07, 2015 at 02:53AM in Technology


What do you think? Is the following code fragment true or false?

"1e1"=="0xa"

Today I learned that this is true. The section Comparison Operators does explain that:

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

So let's see how "numeric string" is defined and compare some other representations of 10:

var_dump(
    0b1010, "10" == "0b1010", // false
    012,    "10" == "012",    // false
    0xa,    "10" == "0xa",    // true
    1E+1,   "10" == "1E+1",   // true
    1e1,    "10" == "1e1",    // true
    10.0,   "10" == "10.0",   // true
    +10,    "10" == "+10"     // true
);

Suprisingly the behaviour is not consistent with the binary and octal representation. Let's ask the PHP guys about that:

The manual section about "String conversions to number" doesn't explicitly mention that hex strings ('0x') are allowed, but neither octal ('0') nor binary ('0b') strings. However, PHP 7 is going remove support for converting hex strings to number.

So they obviously fixed that inconsistent behaviour by changing the definition of "numerical string" and removing the hexadecimal representation from the conversion. This means finally "1e1" == "0xa" won't be true any more. But "10" == "1e1" will still be.

So what did I learn from this? fly.jpg



No one has commented yet.

Leave a Comment

HTML Syntax: Ausgeschaltet