引用 this link .
我知道字符串类型的操作数转换为数字,然后是普通数学
但是请看这些示例代码:
echo intval(1e1); // 10
var_dump("1e1" == 10); // true, and it's ok
echo intval(0x1A); // 26
var_dump("0x1A" == 26); // true, and it's ok
echo intval(042); // 34
var_dump("042" == 34); // fasle, Why ?!!!
为什么最后的代码返回 false。
最佳答案
那是因为 PHP 中的字符串到数字的转换是基于一些古老的 C 函数 - strtod
。其规则为follows :
The expected form of the (initial portion of the) string is optional leading white space as recognized by isspace(3), an optional plus ('+') or minus sign ('-') and then either (i) a decimal number, or (ii) a hexadecimal number [...]
A decimal number consists of a nonempty sequence of decimal digits possibly containing a radix character (decimal point, locale-dependent, usually '.'), optionally followed by a decimal exponent. A decimal exponent consists of an 'E' or 'e', followed by an optional plus or minus sign, followed by a nonempty sequence of decimal digits, and indicates multiplication by a power of 10. [... ]
A hexadecimal number consists of a "0x" or "0X" followed by a nonempty sequence of hexadecimal digits possibly containing a radix character, optionally followed by a binary exponent. [...]
如您所见,“1e1”字符串具有非空序列“1”,后跟一个十进制指数“e1”。因此,它将转换为十进制数 - 变成 10。
'0x1A'字符串遵循十六进制数的规则,将相应地转换为26。但由于没有针对八进制数的特定规则,'042' 将转换为普通十进制 - 并变为 42。当然,这不等于 34。
这不应与 PHP 本身解析 number 文字的方式相混淆。以 0 开头的数字文字被认为代表一个八进制。因此,intval(042)
本质上与 intval(34)
相同 - 但与 intval("042")
不同。
关于php - 比较运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12468116/