Previous | Home | Next |
In Loop Session the for loop is easy and simply than a while loop with a bit more code added to it.
The common tasks that are covered by a for loop are:
- To Set a counter variable to some initial value.
- Check to see if the conditional statement is true.
- Execute the code within the loop.
- Increment a counter at the end of each iteration through the loop.
The for loop is allowing you to define these steps in one easy line of code. It may seem to have a strange form, so pay close attention to the syntax used.
for ( initialize a counter; conditional statement; increment a counter) { do this code; }
Example:
Here is the example of the Copy prices done with a for loop.
<?php $Copy_price = 5; echo "<table border=\"1\" align=\"center\">"; echo "<tr><th>Quantity</th>"; echo "<th>Price</th></tr>"; for ( $counter = 10; $counter <= 100; $counter += 10) { echo "<tr><td>"; echo $counter; echo "</td><td>"; echo $Copy_price * $counter; echo "</td></tr>"; } echo "</table>"; ?>
Output:
Qua Price 10 50 20 100 30 150 40 200 50 250 60 300 70 350 80 400 90 450 100 500
Note: It is important to note that both for loop and while loop implementation of the price chart table are both OK at getting the job done. However, for loop is somewhat more compact and would be preferable in this situation. In later lessons we will see where the while loop should be used instead of for loop.
Previous | Home | Next |