This function searches for the closest element in an array by key value, and returns the key/value pair, or false if not found.
<?php
function nearest($array, $value, $exact=false) {
$next = false;
$prev = false;
$return = false;
if(!isset($array[$value]) && !$exact) {
$array[$value] = '-';
}
if($exact && isset($array[$value])) {
$return = Array($value=>$array[$value]);
} else {
ksort($array); while ( !is_null($key = key($array)) ) {
$val = current($array);
if($key == $value) {
prev($array); $prev = key($array);
next($array); next($array); $next = key($array);
break;
}
next($array);
}
if($prev && $next) {
if(($long - $prev) > ($next - $long)) {
$return = Array($prev=>$array[$prev]);
} else {
$return = Array($next=>$array[$next]);
}
} elseif ($prev || $next) {
if($prev) {
$return = Array($prev=>$array[$prev]);
} elseif ($next) {
$return = Array($next=>$array[$next]);
}
}
}
return $return;
}
?>
Example usage (to lookup the closest color in an array)
<?php
$mycolors= Array(
5001046=>'Abbey',
1774596=>'Acadia',
8171681=>'Acapulco',
6970651=>'Acorn',
13238245=>'Aero Blue',
7423635=>'Affair',
8803850=>'Afghan Tan',
13943976=>'Akaroa',
16777215=>'Alabaster',
16116179=>'Albescent White',
10176259=>'Alert Tan',
30371=>'Allports'
);
$color = 'C0C0C0';
$colorlong = base_convert($color,16,10);
$result = nearest($mycolors, $colorlong, true);
if($result) {
echo "An exact match was found for #" . $color . " which is called '" . $result[key($result)] . "'";
} else {
echo "No exact match was found";
}
if(!$result) {
$result = nearest($mycolors, $colorlong, true);
if($result) {
echo "The closest match for #" . $color . " is #" . base_convert(key($result),10,16) . " which is called '" . $result[key($result)] . "'";
} else {
echo "No match was found for #" . $color;
}
}
?>