PHP将两个不同的字符串表示为相同 [英] PHP expresses two different strings to be the same
问题描述
Possible Duplicate:
php == vs === operator
How do the equality (== double equals) and identity (=== triple equals) comparison operators differ?
为什么以下语句返回true
?
"608E-4234" == "272E-3063"
我也尝试过在字符串周围用单引号引起来.我可以将其评估为false
的唯一方法是使用===
运算符而不是==
I have also tried this with single quotes around the strings. The only way I can get it to evaulate to false
is by using the ===
operator instead of ==
我的猜测是PHP将其视为一种方程式,但似乎有些奇怪.
My guess is PHP is treating it as some sort of equation but it seems a bit of a strange one.
有人可以详细说明吗?
推荐答案
"608E-4234"
是浮点数格式,因此它们在进行比较时会转换为数字.
"608E-4234"
is the float number format, so they will cast into number when they compares.
608E-4234
和272E-3063
都将是float(0)
,因为它们太小了.
608E-4234
and 272E-3063
will both be float(0)
because they are too small.
对于php中的==
,
如果您将数字与字符串进行比较,或者比较涉及 数字字符串,然后将每个字符串转换为数字,然后将 数字比较.
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.
http://php.net/manual/en/language.operators.comparison.php
注意:
Attention:
那同时具有==
和===
的javascript中的行为呢?
What about the behavior in javascript which also has both ==
and ===
?
答案是行为不同于PHP.在javascript中,如果您将两个具有相同类型的值进行比较,则==
与===
相同,因此与两个相同类型的值进行比较不会发生类型转换.
The answer is the behavior is different from PHP. In javascript, if you compare two value with same type, ==
is just same as ===
, so type cast won't happen for compare with two same type values.
在javascript中:
In javascript:
608E-4234 == 272E-3063 // true
608E-4234 == "272E-3063" // true
"608E-4234" == 272E-3063 // true
"608E-4234" == "272E-3063" // false (Note: this is different form PHP)
因此在javascript中,当您知道结果的类型时,可以使用==
而不是===
来保存一个字符.
So in javascript, when you know the type of the result, you could use ==
instead of ===
to save one character.
例如,typeof
运算符总是返回一个字符串,因此您可以只使用
For example, typeof
operator always returns a string, so you could just use
typeof foo == 'string'
而不是typeof foo === 'string'
无害.
这篇关于PHP将两个不同的字符串表示为相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!