I am attempting to find the closest product to the given budget
$array = array(
'productname1' => 5,
'productname2' => 10,
'productname3' => 15
)
$budget = 12;
I have tried using a function like the following to find the nearest value, but it only returns the number which is closest to the budget rather than the product name.
function closest($array, $number) {
sort($array);
foreach ($array as $a) {
if ($a >= $number) return $a;
}
return end($array);
}
I can’t help but think there is a MUCH better implementation of this. Any help would be much appreciated.
Prints:
string(12) "productname2" int(10)Or as a function:
Prints:
Array ( [0] => productname2 // Product Name [1] => 10 // Product Price )Both formats include only three steps:
EDIT: If you don’t care about anything other than the single closest product, then a sort is overkill and a simple
min()function (like Emil used) would be a lot faster. For example: