In PHP, why do the first two of the following statement evaluate true?
<?php
if("00e0" == "00e1") {
echo 'matches (a)';
} else {
echo 'failed (a)';
}
if("00e1" == "00e9") {
echo 'matches (b)';
} else {
echo 'failed (b)';
}
if("00e2" == "00ea") {
echo 'matches (c)';
} else {
echo 'failed (c)';
}
?>
If run this will return the following:
matches (a)
matches (b)
failed (c)
Any string between "00e0", "00e1", "00e2" .. "00e9" will give true if compared with another "00e(0-9)" string.
It's because the strings that are valid floating point values are being interpreted as such.
For example, 00e0
is equivalent to 0 x 100
and 00e9
is equivalent to 0 x 109
, both of which are zero, and hence equal to each other.
However, since 00ea
is not a valid floating point number, it is being treated differently.
You can see a similar effect with:
echo "01e2" - "01e1";
which outputs 90
because it's the same as 1 x 102 - 1 x 101
, or 100 - 10
.
This is supported by the PHP doco (my italics):
If you compare a number with a string or the comparison involves numerical strings, then each string is converted to a number and the comparison performed numerically.
That paragraph links to another page which explains the rules behind conversion, should it happen:
If the string does not contain any of the characters '.', 'e', or 'E' and the numeric value fits into integer type limits (as defined by PHP_INT_MAX), the string will be evaluated as an integer. In all other cases it will be evaluated as a float.
If you want to avoid this behaviour, there's a note in that first link which states you should use ===
instead:
The type conversion does not take place when the comparison is === or !== as this involves comparing the type as well as the value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With