3
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
- function array_closest($arr, $val, $below=false) {
- $narr=count($arr);
- if ($narr == 0) {
- return $val;
- }
- if ($narr == 1) {
- return $arr[0];
- }
- sort($arr);
- if ($arr[0] >= $val) {
- return $arr[0];
- }
- if ($arr[$narr - 1] <= $val) {
- return $arr[$narr - 1];
- }
- foreach($arr as $v) {
- if ($v == $val) {
- return $v;
- }
- if ($v > $val) {
- return $below ? $prev : $v;
- }
- $prev=$v;
- }
- }
Comments