Find number which is greater than or equal to N in an array

前端 未结 11 1096
长发绾君心
长发绾君心 2020-11-30 05:47

If I have a PHP array:

$array

With values:

45,41,40,39,37,31

And I have a variable:

$numb         


        
11条回答
  •  孤街浪徒
    2020-11-30 06:26

    You could use array_reduce for this, which makes it more functional programming style:

    function closest($needle, $haystack) {
        return array_reduce($haystack, function($a, $b) use ($needle) {
            return abs($needle-$a) < abs($needle-$b) ? $a : $b;
        });
    }
    

    For the rest, this follows the same principle as the other O(n) solutions.

提交回复
热议问题