我在 PHP 文档中遇到了这个例子:
<?php
$tests = array(
"42",
1337,
0x539,
02471,
0b10100111001,
1337e0,
"not numeric",
array(),
9.1
);
foreach ($tests as $element) {
if (is_numeric($element)) {
echo "'{$element}' is numeric", PHP_EOL;
} else {
echo "'{$element}' is NOT numeric", PHP_EOL;
}
}
?>
输出:
'42' is numeric
'1337' is numeric
'1337' is numeric
'1337' is numeric
'1337' is numeric
'1337' is numeric
'not numeric' is NOT numeric
'Array' is NOT numeric
'9.1' is numeric
“42”之后的五个示例的计算结果均为“1337”。我能理解为什么“1337e0”(科学计数法)会这样,但我不明白为什么其他人会这样。
我找不到任何人在文档的评论中提到它,我也没有发现它在这里被问到,所以谁能解释为什么 '0x539'、'02471' 和 '0b10100111001' 都评估为 ' 1337'。
最佳答案
输出时所有数字都转换为正常表示。这是十进制数字系统和非科学记数法(例如 1e10
- 科学 float )。
十六进制:
十六进制数以 0x
开头,后跟任何 0-9a-f
。
0x539 = 9*16^0 + 3*16^1 + 5*16^2 = 1337
八进制:
八进制数以 0
开头并且仅包含整数 0-7。
02471 = 1*8^0 + 7*8^1 + 4*8^2 + 2*8^3 = 1337
二进制:
二进制数以 0b
开头并包含 0
和/或 1
。
0b10100111001 = 1*2^0 + 1*2^3 + 1*2^4 + 1*2^5 + 1*2^8 + 1*2^10 = 1337
关于PHP 手册 : Number Conversion in Is_Numeric Example 1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39454866/