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:
26 the retrieved number should be 25 1 the retrieved number should be 1 6 the retrieved number should be 17 the retrieved number should be 716 the retrieved number should be 12I 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.
$myArray = array(1,7, 12, 18, 25);
$needle = 11;
$resultKey = array_search(max(array_intersect(array_values($myArray),range(0,$needle))),$myArray);
$result = $myArray[$resultKey];
EDIT
Assumes array values will always be positive integers
Simplified version
$myArray = array(1,7, 12, 18, 25);
$needle = 11;
$result = max(array_intersect(array_values($myArray),range(0,$needle)));
This looks like homework but I'll humour you:
function closestnumber($number, $candidates) {
$last = null;
foreach ($candidates as $cand) {
if ($cand < $number) {
$last = $cand;
} else if ($cand == $number) {
return $number;
} else if ($cand > $number) {
return $last;
}
}
return $last;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With