Reputation: 8348
I want to return the matching item's value in foreach loop. I have tried with the blow code but it is not returning correctly. If the matches with the last item, it won't returns the correct value.
//$bonuses = count => amount
Array
(
[15] => 25
[30] => 50
[46] => 100
)
// getting keys to compare the count
$counts = array_keys($bonuses);
foreach ($bonuses as $count => $bonus) {
if ($total_number_of_products <= next($counts)) {
$tti = 'Items: '. $total_number_of_products. ' Bonus: '. $bonus. '<BR/>';
}
}
The loop should returns the item if less than or equal. If the count is 46
or higher (in this case) the output should 100
. Now it is returning 50
.
Upvotes: 1
Views: 871
Reputation: 147206
You are on the right track, but you need to output the prior bonus value only until you reach the next key. This is one way to do that:
function get_bonus($total_number_of_products) {
$bonuses = array(15 => 25, 30 => 50, 46 => 100);
$bonus = 0;
foreach ($bonuses as $num_products => $next_bonus) {
if ($total_number_of_products < $num_products) break;
$bonus = $next_bonus;
}
return $bonus;
}
Sample usage:
foreach ([10, 20, 30, 45, 46, 50] as $products) {
echo 'Items: '. $products. ' Bonus: '. get_bonus($products). '<BR/>' . "\n";
}
Output:
Items: 10 Bonus: 0<BR/>
Items: 20 Bonus: 25<BR/>
Items: 30 Bonus: 50<BR/>
Items: 45 Bonus: 50<BR/>
Items: 46 Bonus: 100<BR/>
Items: 50 Bonus: 100<BR/>
Note you can make a minor simplification by adding a 0 => 0
entry to $bonuses
, then you can remove the $bonus = 0
line i.e.
function get_bonus($total_number_of_products) {
$bonuses = array(0 => 0, 15 => 25, 30 => 50, 46 => 100);
foreach ($bonuses as $num_products => $next_bonus) {
if ($total_number_of_products < $num_products) break;
$bonus = $next_bonus;
}
return $bonus;
}
Upvotes: 1