Reffer 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本身如何解析数字文字相混淆.以0开头的数字文字被认为代表十八进制.因此,intval(042)与intval(34)基本相同 – 但与intval(“042”)不同.