The Creamy Bagel Company wants to show a pricing matrix on their website for up to a 20 bagel pack. But, since bagels are a valuable commodity, the price fluctuates regularly.
You have to change it. You love your job.
Using a While Loop and some HTML, this can happen with relative ease, and you’ll only have to change one value when the bagel price changes (then charge for 3 hours of work!).
Read on...
<?php
$bagel_price = 2.15; //This is the price of one bagel
$counter = 1;
echo "<table border=\"1\" align=\"center\">"; //note the escapes for quotes!
echo "<tr><th>Quantity</th>";
echo "<th>Price</th></tr>";
while ( $counter <= 20 ) { //we just set the counter limit at 20
echo "<tr><td>";
echo $counter;
echo "</td><td>";
echo $bagel_price * $counter; //here we multiply
echo "</td></tr>";
$counter = $counter + 1; //here we add 1 to the counter and start again
}
echo "</table>";
?>
Our actual Loop code is bolded above.
You’ll see that we set the variables $bagel_price and $counter.
The $counter variable allows us to create a math function to increment the unit price by 1 each time we loop (see the $counter = $counter + 1 part at the bottom of the loop?)
So, while $counter equals less-than-or-equal-to 20, this loop will function.
Once we hit 21, that’s it - no more loop!
See the example below:
Note on PHP Math functions
+ addition (You can use ++ to increment a value by 1)
- subtraction
* multiplication
/ division