TaylorMac TaylorMac - 9 days ago 6
PHP Question

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

If I have a PHP array:

$array


With values:

45,41,40,39,37,31


And I have a variable:

$number = 38;


How can I return the value?:

39


Because that is the closest value to 38 (counting up) in the array?

Regards,

taylor

Answer
<?php
function closest($array, $number) {

    sort($array);
    foreach ($array as $a) {
        if ($a >= $number) return $a;
    }
    return end($array); // or return NULL;
}
?>