phparraysvalidationmultidimensional-arrayisnumeric

Fastest way to return TRUE if all values in a 2d array column are numeric


Are there faster methods to check the existence of a number (not null) in one column of a multidimensional array in php (for instance, number9)?

Attempt:

The if statement below seems to be working okay.

$arr=Array(
    [0] => Array
        (
            [date] => 2019-01-16
            [number1] => 20.4
            [number2] => 20.54
            [number3] => 19.71
            [number4] => 19.73
            [number5] => 70849266
            [number6] => 70849266
            [number7] => -0.65
            [number8] => -3.189
            [number9] => 20.0902
            [string1] => Jan 16
            [number10] => 0.047796070100903
        )
    ... more rows ...
    [21] => Array
        (
            [date] => 2019-01-17
            [number1 => 19.49
            [number2] => 20.51
            [number3] => 19.02
            [number4] => 20.25
            [number5] => 85018421
            [number6] => 85018421
            [number7] => 0.52
            [number8] => 2.636
            [number9] => 19.7988
            [string1] => Jan 17
            [number10] => 0.075411577270313
        )
);


function isNumeric($var){
  if (is_numeric($var)){
    return true;
  } else {
    return false;
  }
}

if ((array_walk(array_column($arr, "number8"), 'isNumeric')) != 1)

Solution

  • Here are my ideas.
    First is to just filter the array for numeric only values and compare to the original:

    function with_array_filter($arr) {
        return $arr == array_filter($arr, 'is_numeric');
    }
    

    The second example uses casting to a float and then back to string, keep in mind that this is not going to be accurate for very big numbers, however seems to be the fastest (if you care about that at all):

    function is_numeric_array_with_cast($arr) {
        foreach ($arr as $b) {
            if ($b != (string)(float)$b) {
                return false;
            }
        }
        return true;
    }
    

    However probably the simplest solution is to just foreach the array inside a function and return early:

    function is_numeric_array_with_func($arr) {
        foreach ($arr as $b) {
            if (!is_numeric($b)) {
                return false;
            }
        }
        return true;
    }
    

    Benchmarked with an array of 20 elements over 100000 iterations on PHP 7.2:

    $falseArray = [
        '1',
        2.5,
        -10,
        32,
        11.0,
        2.5,
        100101221,
        345,
        -10,
        '-10',
        '+10',
        '10',
        12,
        PHP_INT_MAX,
        PHP_INT_MAX + 1.4e5,
        '-10',
        null,
        'a',
        '5',
        5
    ];
    
    Matt Fryer
    Time: 4.8473789691925
    
    is_numeric_array_with_func
    Time:  4.0416791439056
    
    is_numeric_array_with_cast
    Time:  3.2953300476074
    
    with_array_filter
    Time:  3.99729180336