简体   繁体   中英

count value in If statement for different condition's result

Each customers who buy 5 products, they will get bonus of 2 products.

However, each customer who buy 10 products, they will get bonus of 6 products.

The problem now is what if there is customer who buy 26 products?

So the condition will be :

the customer buy

 (10 x 2) //get 6 products x 2 = 12 products bonus/free 

   + 

 (5 x 1) // get 2 products x 1 = 2 products bonus/free

So far here is my condition:

if ($quatity > 4 && $quatity < 10){
    echo "Congrats, you get 2 products free"
}

if ($quatity > 9){
    echo "Congrats, you get 6 products free"
}

The code above is working fine with me if only the customer buy more than 5 or 10 products.

But as I mentioned above, what if the customer buy more than 10 products such as 26 products or 200 products? Should I write if function manually such as if ($quatity > 9){} , if ($quatity > 19){} , if ($quatity > 29){} , if ($quatity > 39){} , and so on,

OR

can anybody figure out the simple way for this?

Thanks in advance!

This code will give you what you want.

It will break down the 10 products bonus, and then see if there are any 5 bonus left to give.

$tenBonus = (int)($quatity / 10);
$fiveBonus = $quatity % 10 > 4 ? 1 : 0;
$bonus = ($tenBonus * 5) + ($fiveBonus * 2);
if($bonus > 0) {
    echo "Congrats, you get ". $bonus ." products free";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM