Well, is the array sorted? If not the sort it with [man]sort()[/man] then you have a couple of options. A straight iteration through the array which will, on average require O(n/2) comparisons before you find the first result above the criteria (and from there it's a one step operation to find the nearest). The alternative is to implement a binary search on the array which will require O(log2n) comparisons I believe. This will be much quicker on average but is a little more complex to implement (not much though).
Straight Iteration
$crit=10;
sort($array);
for($i=0;$i<count($array);$i++) {
if($crit>$array[$i]) {
if(($array[$i]-$array)>($array-$array[$i-1])) {
$closest=$array[$i-1];
} else {
$closest=$array[$i];
}
}
}
echo($closest);
Binary Search
$crit=10;
sort($array);
echo(binarySearch($array, $crit, 0, count($right)));
function binarySearch($array, $crit, $left, $right) {
if($right>$left) {
if($array[$right]-$crit>$crit-$array[$left]) {
return $array[$left];
} else {
return $array[$right];
}
} else {
$mid=floor(($left+$right)/2);
if($array[$mid]==$crit) {
return $crit;
} elseif($crit<$array[$mid]) {
return binarySearch($array, $crit, $left, $mid-1);
} else {
return binarySearch($array, $crit, $mid+1, $right);
}
}
}
Hope This Helps
Dunno about you but I reckon that's a pretty good 999th post 😃
Bubble