简体   繁体   中英

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. The only way that comes to my mind is foreach and then is_numeric for every value, but is that the fastest way?

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

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

Filter the array using 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)!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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