I've got a shopping cart that I am developing and need to figure out a way to match the discount rates to the quantity.
Discount Rates apply at
So 2-4 items would get the 2 item discount, 5-9 items would get the 5 item discount. 10+ items would get the 10 item discount.
Lets say the customer buys 7 items. The code would need to apply the discount rate for 5 items.
I thought about a for loop where it auto increments the value for (int i = 0; i < 5; i++)
however; I'm not sure how to tie the discount rates into that and stop the variable at the correct discount rate.
I also saw a code like this.. (quantity * unitcost) - (int (quantity / 2) * (unitcost / 2))
which that only applies a specific discount for every second item so that wouldnt work.
I searched google for this but kept seeing example of how to do quantity discounts in specific shopping carts.
$quantity = quantity of items in cart
If there is a way to set up discounts as an array and match the closest that way that would be best scenerio unless someone knows a better way.
$discount = array();
$Discount[1] = 0 percent
$Discount[2] = 5 percent
$Discount[5] = 10 percent
$Discount[10] = 20 percent
I'm using these discounts as an example. Discounts are actually going to be pulled in from the product database because different items can have different discount rates.
I wish I could show a code that is partially working but I'm at a loss with this one. Any help would be greatly appreciated.
A simple use of if and elseif would make it easy.
if ($quantity >= 10) {
$discount = 20;
} elseif ($quantity >= 5) {
$discount = 10;
} elseif ($quantity >= 2) {
$discount = 5;
} else {$discount = 0;}
The same logic could be handled with dynamic discounts and quantities retrieved from a database.
And to do it based on your update using values from your database:
$input = array("1"=>"0","2"=>"5","5"=>"10","10"=>"20");
$reversed = array_reverse($input,true);
foreach ($reversed as $qtydiscount => $discount) {
if ($quantity >= $qtydiscount) {
break;
}
}
echo $discount;