Reputation: 191
I'm trying to implement function where user enters a number to the application, for example 101. Based on this number, function should loop through an array and find matching value. If not found, it should find closest values and round up to higher one. I'm not sure how to explain this properly, but here is an example:
Array consists numbers 100, 150, 200.
• User enters number 101. No exact number was found, function should return value 150.
• User enters number 151. No exact number was found, function should return value 200.
• User enters number 150. Exact number was found, function should return value 150.
I've made a function which finds matching or closest value, but this isn't quite what I want, because it doesn't round the number up, in case exact match wasn't found.
$arr(100, 150, 200)
$search = 101;
function getClosest($search, $arr) {
$closest = null;
foreach ($arr as $item) {
if ($closest === null || abs($search - $closest) > abs($item - $search)) {
$closest = $item;
}
}
return $closest;
}
In this case it returns the closest number to 101, which is 100. I would like it to return 150. How can I fix this?
Upvotes: 1
Views: 136
Reputation: 914
You can do something like this. Sort the array first so you can get the next highest value.
<?php
$array = array(100,150,200);
$number = 101;
echo closest($array, $number);
function closest($array, $number) {
sort($array);
foreach ($array as $a) {
if ($a >= $number) return $a;
}
return end($array); // or return NULL;
}
?>
Upvotes: 1