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

前端 未结 11 1087
长发绾君心
长发绾君心 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:27

    Here's a smaller function that will also return the closest value. Helpful if you don't want to sort the array (to preserve keys).

    function closest($array, $number) {
        //does an exact match exist?
        if ($i=array_search($number, $array)) return $i;
    
        //find closest
        foreach ($array as $match) {
            $diff = abs($number-$match); //get absolute value of difference
            if (!isset($closeness) || (isset($closeness) && $closeness>$diff)) {
                $closeness = $diff;
                $closest = $match;
            }
        }
        return $closest;
    }
    

提交回复
热议问题