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

Your comment:
[p] [b] [i] [u] [s] [quote] [pre] [br] [code] [url] [email] strip help 2000

===

Enter a maximum of 2000 characters.
Improve the presentation of your text with the following formatting tags:
[p]paragraph[/p], [b]bold[/b], [i]italics[/i], [u]underline[/u], [s]strike[/s], [quote]citation[/quote], [pre]as is[/pre], [br]line break,
[url]http://www.izend.org[/url], [url=http://www.izend.org]site[/url], [email]izend@izend.org[/email], [email=izend@izend.org]izend[/email],
[code]command[/code], [code=language]source code in c, java, php, html, javascript, xml, css, sql, bash, dos, make, etc.[/code].