I have an array, for example (it can be anything, but it's already ordered):
array(1,7, 12, 18, 25);
I need to find what number is the closest to that array.
Taking the above array:
$needle = 11;
The number in array i want to retrieve is 7
.
The closest number to 11
should be 12
, but i dont want the closest number, i want the minor closest number, if that makes any sense.
Another examples:
- Entering
26
the retrieved number should be25
- Entering
1
the retrieved number should be1
- Entering
6
the retrieved number should be1
- Entering
7
the retrieved number should be7
- Entering
16
the retrieved number should be12
I found a nice function, but it does only retrieve the closest number, and not the minor closest 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.