View Single Post
  #16 (permalink)  
Old 03-13-2009, 08:06 AM
grace55 grace55 is offline
Administrator
Site Admin
 
Join Date: Jun 2008
Posts: 342
Default A journey leads to php....

LOOPS

We all have mundane, repetitive tasks we have to do. You know, like putting stamps on all those holiday greeting cards we send out every year? Well, from a programming angle, PHP can help us ease the workload on repetitive tasks in websites with a LOOP.

The first one we’ll discuss is the WHILE LOOP. It sounds like a weird carnival ride (I got sick on the While Loop - it was great!) but it is one of the most useful loop functions in PHP.

Logically, it looks like this:

while ( this conditional statement is true){
//do this;
}


This isn’t real code - just an illustration of how it works. now, here’s what happens, step by step:

1. PHP checks the conditional statement. If it is true, move to step 2. If it is false, go to step 4.
2. PHP runs the code contained in the loop.
3. We go back to step 1 and start again, making a LOOP.
4. Once the conditional statement becomes false, the loop exits, and code placed after the loop runs.

Real World Usage for WHILE LOOPS

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 highlighted in blue 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!

Note on PHP Math functions

+ addition (You can use ++ to increment a value by 1)
- subtraction
* multiplication
/ division

What it looks like in a browser...and you can see at-a-glance what 13 bagels will cost you!
__________________
Christian Prayer Forum
Reply With Quote