1

arrayclosest

array_closest
SYNOPSIS

array_closest($arr, $val, $below=false)

DESCRIPTION

array_closest returns the value in the array $arr which is the closest to $val. If $below is true, array_closest returns the closest value which is inferior. If $below is false, array_closest returns the closest value which is superior. If $val is smaller than the smallest value in $arr, this value is returned. If $val is larger than the largest value in $arr, this value is returned.

CODE
  1. function array_closest($arr, $val, $below=false) {
  2.     $narr=count($arr);
  3.  
  4.     if ($narr == 0) {
  5.         return $val;
  6.     }
  7.  
  8.     if ($narr == 1) {
  9.         return $arr[0];
  10.     }
  11.  
  12.     sort($arr);
  13.  
  14.     if ($arr[0] >= $val) {
  15.         return $arr[0];
  16.     }
  17.     if ($arr[$narr - 1] <= $val) {
  18.         return $arr[$narr - 1];
  19.     }
  20.  
  21.     foreach($arr as $v) {
  22.         if ($v == $val) {
  23.             return $v;
  24.         }
  25.         if ($v > $val) {
  26.             return $below ? $prev : $v;
  27.         }
  28.         $prev=$v;
  29.     }
  30. }

Comments

To add a comment, click here.