检查数组中的所有值是否为数字的最快方法是什么?

rsk*_*k82 14 php arrays

我必须检查大数组,看看它们是否100%填充数值.我想到的唯一方法是foreach,然后是每个值的is_numeric,但这是最快的方法吗?

bco*_*sca 20

假设你的数组是一维的,只是由整数组成:

return ctype_digit(implode('',$array));
Run Code Online (Sandbox Code Playgroud)

  • @ user393087:如果你可以备份你的内爆是昂贵的主张,你的"我认为"评论没有根据.真正的程序员说"我检查过".这就是为什么基准测试是一门科学. (4认同)
  • 不得不取消我的投票,`false`和`NULL`值,为`is_numeric()`返回false会在这里被破坏为空字符串,转义`ctype_digit()`. (3认同)

Man*_*ncy 5

array_map("is_numeric", array(1,2,"3","hello"))

Array ( [0] => 1 [1] => 1 [2] => 1 [3] => )
Run Code Online (Sandbox Code Playgroud)


小智 5

使用is_numeric过滤数组。如果结果的大小与原始大小相同,则所有项目均为数字:

$array = array( 1, '2', '45' );
if ( count( $array ) === count( array_filter( $array, 'is_numeric' ) ) ) {
    // all numeric
}
Run Code Online (Sandbox Code Playgroud)