Search code examples
phparraysmin

How to find the n smallest value in array using php?


I have an array As :

$array = array(
0 => 1,
1 => 3,
2 => 7,
3 => 0,
4 => 6,
5 => 3,
);

How to find n smaller number in array? (e.g: n = 4, result is: 0,1,3,3)


Solution

  • For cases where you have huge arrays and need your code to run in O(n) instead of O(n.log(n)), you could use this function:

    function min4($array) {
        $result = [1e300,1e300];
        foreach ($array as $val) {
            if ($val <= $result[1]) {
                array_splice($result, $val > $result[0] ? 1 : 0, 0, [$val]);
            } elseif ($val <= $result[3]) {
                array_splice($result, $val > $result[2] ? 3 : 2, 0, [$val]);
            }
        }
        return array_slice($result, 0, 4);
    }
    

    Call as:

    print_r (min4($array));
    

    Of course, for arrays of moderate size, using sort will give better performance. But already for arrays with more than 300 elements, the above function will perform better in most cases.