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

The FOR LOOP

The FOR LOOP is very similar to a WHILE LOOP. The difference being a little bit more code is contained in the loop. The FOR LOOP can be a little more compact than a WHILE LOOP. Here’s the logic:

for ( create a counter; conditional statement; increment the counter){
do this;
}

Let’s use our fluctuating bagel cost from above and write this out. Oops - bagels just went up 10 cents!

<?php
$bagel_price = 2.25;
echo "<table border=\"1\" align=\"center\">";
echo "<tr><th>Quantity</th>";
echo "<th>Price</th></tr>";
for ( $counter = 1; $counter <= 20; $counter += 1) {
echo "<tr><td>";
echo $counter;
echo "</td><td>";
echo $bagel_price * $counter;
echo "</td></tr>";
}
echo "</table>";
?>



Once again, the loop is highlighted in blue. You’ll notice that the counter is defined inside the loop as opposed to a variable outside.
And..to the right, you’ll see the output.
There’s one more Loop we’re going to cover, isn’t this exciting? Hello? Still there?
The FOR EACH Loop
What if you want to loop through an Associative Array? (See? Told you we’d get back to this!) You can use FOR EACH to do this task. Where the WHILE and FOR loops run until an error is encountered, the FOR EACH loop will run through every element in the array.
Let’s revisit the associative array we set up with the trucks...

<?php
$truck[“Toyota”] = Tundra;
$truck[“Nissan”] = Titan;
$truck[“Dodge”] = Ram;
?>

To loop through the Makers / Models, we’d use this code:

<?php
foreach( $truck as $make => $model){
echo "Make: $make, Model: $model <br />";
}
?>


The code is written in a strange way, it isn’t obvious how it works. Let’s look at it in a simpler way:

$something as $key => $value

So, in english... FOR each thing in the array, I want to refer to the key as $key and the value as $value. The operator ‘=>’ indicates the relationship between the key and the value...the key “points” to the value.
I think that’s about all we need to cover with Loops.
Next up...
__________________
Christian Prayer Forum
Reply With Quote