简体   繁体   中英

How to find a number which is less than and closest to number X in an array?

For example I have array:

Array(
  [0] => 15
  [1] => 6
  [2] => 19
  [3] => 21
  [4] => 18
)

If current time is 20 then I need value 19 (which is less than and near to 20)

similarly if I pass my X number as 17 it will return 15 from array.

If 7 then it should return 6.

Please suggest how to achieve that with PHP?

Thanks!

You can create your custom function using array_filter and end function like as

function find_closest($arr,$x){
    sort($arr);
    $filtered_array = array_filter($arr,function($v)use($x){ 
        return $v < $x;
    });
    return count($filtered_array) > 0 ? end($filtered_array) : "Your Message";
}

echo find_closest($arr,17);

Demo

I would do it the following way. I think that's a little cleaner (and probably faster) than the accepted answer:

function closest($arr, $x) {
    $result = "default";
    sort($arr);

    foreach($arr as $value) {
        if($value < $x) {
            $result = $value;
        } else
            break;
    }
    return $result;
}

Push the element that you're trying to find, in your array.

array_push($your_array, "17");
$arr = asort($your_array);
$key = array_search('17', $arr); 

The value will be in $arr[$key-1] . Hope this helps you out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM