Search code examples
phpformulashopping-cartdiscountcoupon

formula discount 2x1 3x2 etc PHP


I'm stuck thinking about how to do this: I have a shopping cart and I want to create a coupon system with 2x1, 3x2, 5x3 discount, etc.

But I can't solve this to get a formula and show the total price after apply the coupon.

For example: item price: $5 usd and I have a coupon 2x1:

If I buy 2 items: TOTAL: $5,00 usd (2x1)
If I buy 3 items: TOTAL: $10,00 usd (2x1 + 1)
If I buy 4 items: TOTAL: $10,00 usd (2x1 + 2x1)

In the same way. Item price: $5 usd. and now I have a coupon 3x1.

If I buy 2 items: TOTAL: $10,00 usd (3x1 NOPE!)
If I buy 3 items: TOTAL: $5,00 usd (3x1)
If I buy 4 items: TOTAL: $10,00 usd (3x1 + 1)
If I buy 5 items: TOTAL: $15,00 usd (3x1 + 2)
If I buy 6 items: TOTAL: $10,00 usd (3x1 + 3x1)
If I buy 7 items: TOTAL: $15,00 usd (3x1 + 3x1 + 1)



How to obtain the total price using the coupon in PHP?


Solution

  • Another solution:

    function calc($item_count, $unit_price, $coupon)
    {
      list($need, $paid) = explode('x', $coupon);
      $left = $item_count % $need;
      return $unit_price * (intval($item_count / $need) * $paid + $left);
    }