来自is_numeric / foreach例程的意外输出

时间:2017-12-06 16:04:14

标签: php foreach

参考:http://php.net/manual/en/function.is-numeric.php

示例#1 is_numeric()。

为什么示例#1例程输出1337次而不是1次?我的期望是例程将输出1337之后的其他3个数值。即使我重新排列元素的顺序,它仍然输出1337 4次。我理解不允许使用十六进制和二进制值,但为什么例程输出1337这些值。此外,如果我将1337更改为01337,则输出为735.

为什么这些令人困惑的输出?

<?php
$tests = array(
    "42", 1337, 0x539, 02471, 0b10100111001, 1238.443e2, "not numeric",
    array(), 9.1, null
);

foreach ($tests as $element) {
    if (is_numeric($element)) {
        echo var_export($element, true) . " is numeric", PHP_EOL;
    } else {
        echo var_export($element, true) . " is NOT numeric", PHP_EOL;
    }
}
?>

Output:
'42' is numeric
1337 is numeric
1337 is numeric
1337 is numeric
1337 is numeric
123844.300000000002910383045673370361328125 is numeric
'not numeric' is NOT numeric
array () is NOT numeric
9.0999999999999996447286321199499070644378662109375 is numeric    
NULL is NOT numeric

2 个答案:

答案 0 :(得分:1)

Base-N表示法语法

您必须知道将其拉下来

十六进制

前缀为0x的数字将被解释为base-16

Octtal

前缀为0的数字将被解释为base-8

二进制

前缀为0b的数字将被解释为base-2

转换为十进制

  • 1337 base10(base10 value:1337)
  • 0x539 base16(base10 value:1337)
  • 02471 base8(base10 value:1337)
  • 0b10100111001 base2(base10 value:1337)

字符串中的数字始终显示在base-10

将这些数字转换为字符串(与var_export一样)会将它们转换为base-10,除非您使用number_format

答案 1 :(得分:0)

因为这是你的价值观。

例如,如果您启动一个零的数字,则意味着,此数字是八进制数字系统。十进制数系统中的02471 = 1337。另一个是hexa,剩下的是二进制文件。