简体   繁体   English

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

[英]What is the Quickest Way to Check If All Values in an Array Are Numeric?

I must check big arrays to see if they are 100% filled with numeric values.我必须检查大数组以查看它们是否 100% 填充了数值。 The only way that comes to my mind is foreach and then is_numeric for every value, but is that the fastest way?我想到的唯一方法是 foreach 然后是每个值的 is_numeric,但这是最快的方法吗?

假设您的数组是一维的并且仅由整数组成:

return ctype_digit(implode('',$array));

Filter the array using is_numeric.使用 is_numeric 过滤数组。 If the size of the result is the same as the original, then all items are numeric:如果结果的大小与原始大小相同,则所有项目都是数字:

$array = array( 1, '2', '45' );
if ( count( $array ) === count( array_filter( $array, 'is_numeric' ) ) ) {
    // all numeric
}
array_map("is_numeric", array(1,2,"3","hello"))

Array ( [0] => 1 [1] => 1 [2] => 1 [3] => )

I know this question is rather old, but I'm using Andy's approach in a current project of mine and find it to be the most reliable and versatile solution, as it works for all numerical values, negative, positive, and decimal alike.我知道这个问题相当古老,但我在我当前的一个项目中使用了安迪的方法,并发现它是最可靠和通用的解决方案,因为它适用于所有数值,负数、正数和小数。

Here's an average value function I wrote:这是我写的平均值函数:

$array = [-10,1,2.1,3,4,5.5,6]; // sample numbers
function array_avg($arr) {
    if (is_array($arr) && count($arr) === count(array_filter($arr, 'is_numeric'))) {
        return array_sum($arr)/count($arr);
    } else {
        throw new Exception("non-numerical data detected");
    }
}
echo array_avg($array); // returns 1.6571428571429

This small function works fine for me这个小功能对我来说很好用

function IsNumericarr($arr){
    if(!is_array($arr)){
        return false;
    }
    else{
        foreach($arr as $ar){
            if(!is_numeric($ar)){
                return false;
                exit;
            }
        }
        return true;
    }
}

Loop is needed需要循环

if(array_reduce($array, function($c, $v){return $c & (int)is_numeric($v);}, 1))

The quickest way might be to just assume they're all numerals and continue on with your operation.最快的方法可能是假设它们都是数字并继续您的操作。 If your operation fails later on, then you know something isn't a numeral.如果您的操作稍后失败,那么您就知道某些东西不是数字。 But if they are all actually numerals... you can't get much faster than O(0)!但如果它们实际上都是数字......你不能比 O(0) 快得多!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM