Re: Advice needed

From: Date: Sat, 23 Mar 2002 22:29:01 +0000
Subject: Re: Advice needed
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-89856@lists.php.net to get a copy of this message
Actually, it looks pretty straight-forward: <?php $points = array( 1, 2, 3, 5, 10, 15, 20, 25, 50, 100, 300, 500, 600, 1000000000 ); $prices = array(); function init_prices() { global $points, $prices; foreach($points as $val) $prices[$val] = "none"; } function show_prices() { global $points, $prices; foreach($points as $val) echo "q$val: ".$prices[$val]."<br />"; } function add_price_point($num, $price) { global $points, $prices; // this saves us from div-by-0 and automatically // discards invalid quantities if ($num < 1) return; $per = $price / $num; foreach($points as $val) if ($val >= $num) if (($prices[$val] == "none") or ($prices[$val] > $per)) $prices[$val] = $per; } init_prices(); add_price_point($Quantity1, $Price1); add_price_point($Quantity2, $Price2); add_price_point($Quantity3, $Price3); show_prices(); ?> > q1 q2 q3 q5 q10 q15 q20 q25 q50 q100 q300 q500 q600 q1000000000 > 0 0 0 0 .10 .10 .10 .10 .10 .10 .10 .10 .10 .10 Note that this is a messy and misleading way to do things: 1. Having '0' as the price for un-valued quantities is dangerous, unless you want to tell me that 4 or fewer items are free. Note that in my code I have replaced it with "none", which isn't much safer (it may get cast to 0) but is a lot more obvious when debugging. 2. What's with all these price points? Surely it would be cleaner to keep just the decision points in your database instead? - what happens if you can get a cheaper price on 120 items (or on any arbitrary number of items not in the list)? Will you just defer it to the next number of items (in my example, 300)? Your customers might be unhappy... > Now the tricky part is $Quantity2 can either be blank or have a value > and if $Quantity2 has a value then $Quantity3 can either be blank or have a > value This is quite simply - let the function itself check whether it has been passed a valid quantity - if not, return without doing anything. Voila - valid results and code that is easy to read.

« previous php.general (#89856) next »