Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 422
TaylorMac Avatar asked May 27 '11 02:05

TaylorMac


1 Answers

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

    sort($array);
    foreach ($array as $a) {
        if ($a >= $number) return $a;
    }
    return end($array); // or return NULL;
}
?>
like image 26
fardjad Avatar answered Nov 01 '22 16:11

fardjad