for loops
For loops are the most complex loops in PHP. The syntax is a little different from a while loop. There are three different expressions contained within the parenthesis of a for loop, as shown below:
<?php
|
|
The first expression is performed at the beginning of the loop, no matter what. This is similar to declaring the "$i" or similar variable with while loops.
The second expression is evaluated at the beginning of each iteration. If it evaluates to true, the loop continues and the actions between the curly braces are executed. This is similar to the conditional of while loops.
The third expression is performed at the end of each iteration. The most commonly used expression here is something similar to "$i++" Do you see how for and while loops are somewhat similar?
Let's try the same example we used for while loops:
<?php
|
|
Do you see how for loops sort of compact everything inside of the parenthesis? The variable declartion, conditional statement and incrementing of the variable are all done inside of the parenthesis. This can make your code smaller and more efficient.
You may be wondering what loops are useful for. After all, any idiot can count to ten without PHP's help. Loops are most effective when used in combination with arrays. You can use loops to iterate over each item in your array giving you virtually limitless opportunities.
I'll show you an example. You could possibly even modify this code to make your own comment system.
<?php
|
|
This example uses a multidimensional array. Each item in the $comments array is an array itself, containing a name and a message item. We use a for loop to iterate through each item in the $comments array and echo the name and message of each comment. This is a really simple example, but it does demonstrate one good use of for loops.
That's all for this tutorial. In summary: We covered three types of loops in PHP; while, foreach and for. Experiment with each of them and if you have any questions or comments, feel free to post them below.
| Discuss Tutorial: Using Loops in PHP | 4 Comments |
I used it for my birthday drop-down boxes 
!!
























