I have an array, for example (it could be anything, but it's already ordered):
array(1,7, 12, 18, 25);
I need to find which number is closest to this array.
Taking the specified array:
$needle = 11;
The number in the array I want to get is 7. The closest number to 11should be 12, but I don't want the nearest number, I want the lowest nearest number, if that makes sense.
Other examples:
- Enter
26, the received number should be25 - Enter
1, the received number should be1 - Enter
6, the received number should be1 - Enter
7, the received number should be7 - Enter
16, the received number should be12
I found a nice function, but it only returns the nearest number, not the lowest nearest number:
function closestnumber($number, $candidates) {
for($i = 0; $i != sizeof($candidates); $i++) {
$results[$i][0] = abs($candidates[$i] - $number);
$results[$i][1] = $i;
}
sort($results);
$end_result['closest'] = $candidates[$results[0][1]];
$end_result['difference'] = $results[0][0];
return $end_result;
}
$closest = closestnumber(8,array(1,7, 12, 18, 25));
echo "Closest: ".$closest['closest']."<br>";
echo "Difference: ".$closest['difference'];
Thanks in advance.
source
share