1

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.

2
  • So the bonus for 10 products is 0? and 40 would be 50? Commented Jan 11, 2021 at 6:49
  • That's correct. It's a flat bonus. User will get only when the count reaches to the number. No in-betweens. Commented Jan 11, 2021 at 6:56

1 Answer 1

1

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/>

Demo on 3v4l.org

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.