开发者

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

I must check b开发者_Go百科ig 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?


assuming your array is one-dimensional and just made up of integers:

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)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜