为什么("00e0&" =="00e1")评估为true? [英] Why does ("00e0" == "00e1") evaluate as true?
问题描述
在PHP中,为什么以下语句的前两个结果为true?
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)
与其他"00e(0-9)"字符串相比,"00e0","00e1","00e2" .."00e9"之间的任何字符串都为真.
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.
例如,00e0
等同于0 x 100
,00e9
等同于0 x 109
,两者都为零,因此彼此相等.
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.
但是,由于00ea
不是 个有效的浮点数,因此对它的处理方式有所不同.
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";
之所以输出90
,是因为它与1 x 102 - 1 x 101
或100 - 10
相同.
which outputs 90
because it's the same as 1 x 102 - 1 x 101
, or 100 - 10
.
PHP doco (斜体字)支持:
如果将数字与字符串进行比较,或者比较涉及数字字符串,则将每个字符串转换为数字,然后以数字方式进行比较.
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:
如果字符串不包含任何字符.","e"或"E",并且数值适合整数类型限制(由PHP_INT_MAX定义),则字符串将被评估为整数.在所有其他情况下,它将被视为浮点数.
如果您要避免这种行为,则在第一个链接中有一条注释,指出您应改用===
:
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.
这篇关于为什么("00e0&" =="00e1")评估为true?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!