Page 1 of 1

Help with discount function

Posted: Mon Dec 26, 2011 3:24 pm
by koffeehaus
Hello, I'm designing a website for my mate's restaurant, and I am seriously stuck with discounts.

Okay the code calculates the total [$price] but I have no clue how to discount above certain price.

Say if a person spends more than £20 there should be a £2.50 discount; if above £30 then there is £4; and above £40 there is a £5 discount.

If you guys can help me I would dearly appreciate it, as it drives me bonkers right now.

Thanks & cheers,

Dan.

Re: Help with discount function

Posted: Mon Dec 26, 2011 4:33 pm
by Celauran
If those are the only criteria, it could be most simply done with a few if statements.

Code: Select all

$discount = 0;
if      ($price > 40) { $discount = 5; }
else if ($price > 30) { $discount = 4; }
else if ($price > 20) { $discount = 2.50; }

Re: Help with discount function

Posted: Tue Dec 27, 2011 2:32 pm
by koffeehaus
Celauran wrote:If those are the only criteria, it could be most simply done with a few if statements.

Code: Select all

$discount = 0;
if      ($price > 40) { $discount = 5; }
else if ($price > 30) { $discount = 4; }
else if ($price > 20) { $discount = 2.50; }

It worked! Thank you big time! Now I can bloody rest in peace. These three small LOCs have cost me over a week of brainhurt, almost embarrassing that is. Anyways, thnx again & happy New Year.

Re: Help with discount function

Posted: Tue Dec 27, 2011 5:25 pm
by twinedev
Another method, which makes it easier to adjust later on, because the Limits/Discounts are in a single line: (and if you have a main configuration file, can set it there with other site specific information, and/or read it out of a database so the owner can change them through an admin panel)

Code: Select all

<?php
	$aryDiscount = array(20=>2.50,30=>4.00,40=>5.00);
	krsort($aryDiscount); // Allows you to enter them in any order


	$fPrice = 34.22; // Price we are working with
	$fDiscount = 0.00; // Default of nothing
	foreach($aryDiscount as $fMin=>$fAmt) {
		if ($fPrice >= $fMin) {
			$fDiscount = $fAmt;
			break;
		}
	}

	$fTotal = $fPrice = $fDiscount;
?>
Also, to streamline it more, you can add 0=>0.00 to the definition of the array, then it will always at least match that, so the foreach can directly assign $fDiscount:

Code: Select all

<?php
	
	$aryDiscount = array(0=>0.00,20=>2.50,30=>4.00,40=>5.00);
	krsort($aryDiscount); // Allows you to enter them in any order


	$fPrice = 34.22; // Price we are working with
	foreach($aryDiscount as $fMin=>$fDiscount) {
		if ($fPrice >= $fMin) break;
	}

	$fTotal = $fPrice = $fDiscount;
?>