Search code examples
phparraysfilteringminarray-column

Find minimum value in column of 2d array which is not zero


I am using the following code to echo the minimum value in an array:

$array = [
    ['a' =>  0, 'f' => 0, 'l' => 61.60],
    ['a' => 38, 'f' => 0, 'l' => 11.99],
    ['a' => 28, 'f' => 0, 'l' =>  3.40],
];
$min = min(array_column($array, 'a'));
echo $min;

Now I want to exclude 0 from the results, I know I can use array_filter() to achieve this, but do I need to process the array twice?


Solution

  • Yes, this will do:

    $min = min(array_filter(array_column($array, 'a')));
    

    It will iterate the array three times, once for each function.

    You can use array_reduce to do it in one iteration:

    $min = array_reduce($array, function ($min, $val) {
        return $min === null || ($val['a'] && $val['a'] < $min) ? $val['a'] : $min;
    });
    

    Whether that's faster or not must be benchmarked, a PHP callback function may after all be slower than three functions in C.

    A somewhat more efficient solution without the overhead of a function call would be a good ol' loop:

    $min = null;
    foreach ($array as $val) {
        if ($min === null || ($val['a'] && $val['a'] < $min)) {
            $min = $val['a'];
        }
    }
    

    In the end you need to benchmark and decide on the correct tradeoff of performance vs. readability. In practice, unless you have positively humongous datasets, the first one-liner will probably do just fine.