In chapter 3, you learned how to manipulate conditional statements. In additional to controlling the conditions required to execute a part of codes, you may wish to learn how to control the number of times a script is run. To do this, you will need iteration, or loop. There are four types of Loops you can use in PHP, they are:
While Statement
Do...while Statement
For Statement
For each Statement
In this thread we will be dealing with the first three types. The last one requires knowledge of arrays, so I will bring it up later when we reach chapter 6 - PHP Arrays.
1. While Statement:
While Statement is among the most commonly used loops in any programming languages. Most aspiring programmers begin learning PHP iteration statements with while loops instead of do...while or for loops. The basic syntax of a while statement is:
PHP Code:
while(expression){
// your codes here
}
Its syntax looks somewhat similar to if...else statement, with an expression to be evaluated inside parenthesis and PHP codes to execute enclosed in brackets. An example of a while loop is written below:
PHP Code:
$num = 0;
while($num <=5){
echo "The number is: $num. </br>";
}
The loop works, it causes no syntax error. Nonetheless, this is not a good practice at all, since we have apparently left out one important factor in this program. This is what we refer to as counter, without which a loop will continue to run forever. In most of the times, your goal is to have a certain part of codes to execute a few times, but not endlessly. Because of this, you will need to add a counter to the PHP codes, which normally increments or decrements each time a loop runs. Allow me to illustrate the idea of counter with this example:
PHP Code:
$num = 0;
while ($num <=5){
echo "The number is: $num. </br>";
$num ++;
}
The program goes through the loop six times(from $num ==0 to $num ==5) and yields the following result, just as we have expected.
PHP Code:
The number is: 0.
The number is: 1.
The number is: 2.
The number is: 3.
The number is: 4.
The number is: 5.
To avoid running into endless loops that may cause severe server load issues, it is a good practice to always keep an eye on your counter. The counter should always be matched at some point so that a loop will stop executing.
2. Do...while Statement:
Do...while statement is similar to while statement to some extent, and they can be used as substitutes for most of the time. The syntax for a Do...while loop can be viewed below:
PHP Code:
do{
//your codes here
}while(expression);
Here the codes to execute are enclosed in brackets between the do and while keywords. The while(expression) line must end with a semicolon, or you will receive a fatal error message from the screen. One may ask if there's a difference between a do...while loop compared to while loop. To answer this question, let us compare an extreme example of codes written in both a while and a do...while statement:
PHP Code:
$num = 0;
while($num < -1){
echo "The current number is: $num </br>";
$num++;
}
PHP Code:
$num = 0;
do{
echo "The current number is $num </br>";
$num++;
}while($num < -1);
The result may seem surprising. The while loop returns nothing on the screen, since the condition for the while statement is not satisfied. The do...while loop, however, prints the line "The current number is 0" on the screen. You may have understood the difference already, a do...while loop shall at least execute for one time no matter whether the condition in while statement is met, but the while statement does not. At times when you want your loop to execute at least one time whatever the condition is, use a do...while loop instead of a while loop.
3. For Statement:
The for statement is no different from while statement when it comes to functionality, but it looks a lot neater and usually improves performances to a certain extent. The syntax of a for loop is:
PHP Code:
for(Initialization expression;Final/Test expression;Counter expression){
// your codes here
}
To see how a while statement and a for statement can be converted from each other, I will write a program with for statement that yields completely the same result as we had above for a while loop:
PHP Code:
for($num = 0; $num <=5; $num++){
echo "The number is: $num</br>";
}
The result is indeed exactly the same as before, thus it is possible and easy to inter-convert between while and for loops. One can see from the codes above that a for loop does make a script much more clear and easier to read.
Also the definition of counter is usually defined inside the parenthesis as initialization expression, not somewhere outside of the loop. Because of this, programmers may enjoy the usage of for loops a lot if they tend to forget the counter statement in while or do...while loops.
If the counter is by any chance pre-defined in a previous code, one may simply skip the counter initialization expression, but leave the semicolon inside parenthesis:
PHP Code:
$num = 0;
for(; $num <=5; $num++){
echo "The number is: $num</br>";
}
The result is apparently the same as before, which makes a for loop more flexible. It is not recommended for beginners though, since forgetting the semicolon in initialization expression may cause severe issues.
4. Advanced Loops with break and continue:
There are times that you may wish to exit a loop when an expression is impossible to execute at certain points. Below is a good example:
PHP Code:
$num = -5;
for(;$num <=5;$num++){
$num2 = 10;
echo "The number ".$num2." divided by ".$num." is ".$num2/$num."!</br>";
}
The counter $num increments by 1 each time the loop runs. At one point the value becomes 0, but we all know from Math that dividing by 0 will give an undefined number. This can cause severe issues in PHP, and should be prevented at any time. By using the break statement, we can force the loop to end if it reaches a point like this:
PHP Code:
$num = -5;
for(;$num <=5;$num++){
if($num == 0){
echo "We cannot divide a number by 0!";
break;
}
$num2 = 10;
echo "The number ".$num2." divided by ".$num." is ".$num2/$num."!</br>";
}
The result is shown below, in which we have successfully exit a loop when the denominator becomes 0:
PHP Code:
The number 10 divided by -5 is -2!
The number 10 divided by -4 is -2.5!
The number 10 divided by -3 is -3.33333333333!
The number 10 divided by -2 is -5!
The number 10 divided by -1 is -10!
We cannot divide a number by 0!
You may, however, wish to continue this loop while only to skip one execution when the denominator becomes 0. It is completely possible to do this, simply replace the break statement with continue statement:
PHP Code:
$num = -5;
for(;$num <=5;$num++){
if($num == 0){
echo "We cannot divide a number by 0!</br>";
continue;
}
$num2 = 10;
echo "The number ".$num2." divided by ".$num." is ".$num2/$num."!</br>";
}
Here is our new result printed on the screen. You may notice that the script does skip the execution of 10/0, while continuing to run the loop till it hits the final expression:
PHP Code:
The number 10 divided by -5 is -2!
The number 10 divided by -4 is -2.5!
The number 10 divided by -3 is -3.33333333333!
The number 10 divided by -2 is -5!
The number 10 divided by -1 is -10!
We cannot divide a number by 0!
The number 10 divided by 1 is 10!
The number 10 divided by 2 is 5!
The number 10 divided by 3 is 3.33333333333!
The number 10 divided by 4 is 2.5!
The number 10 divided by 5 is 2!
You can see that the usage of break and continue statement makes a loop a lot more flexible. They may seem hard to comprehend at this moment, but you will get used to them with time.
5. Nesting Loops:
Just like conditional statements, it is possible to use a child iteration inside a parent iteration. You can even enclose a while statement inside a for statement, and vice-versa. The syntax of nesting loops is shown below, we will use for loops here:
PHP Code:
for(initialization expression 1; final expression 1; counter1){
// your codes here
for(initialization expression 2; final expression 2; counter2){
// your codes here
}
}
A nesting loop can achieve lots of goals we otherwise cannot accomplish, but they are also harder for other programmers to understand. In a long PHP script, it is also quite common for even advanced programmers to leave out a bracket. My advice is therefore, be cautious with nesting loops. Nesting loops are indeed powerful tool though, I will write a multiplication table below so you can get a feel of how beautiful the art of PHP programming can be:
PHP Code:
echo "//";
$row = 1;
$col = 1;
for(; $col<=9; $col++){
// print the column bar
echo " $col ";
}
echo "</br>";
for($i = 1; $i<=9; $i++){
echo "$row";
// print the row bar
for($j = 1; $j<=9; $j++){
// here's the body of multiplication table
$m = $i*$j;
echo " $m ";
}
echo "</br>";
$row++;
}
The result shows up pretty nicely, even though spacing is still a problem. In order to solve this problem, we will have to use the printf() function for strings, which I shall demonstrate in chapter 7 - Strings:
PHP Code:
// 1 2 3 4 5 6 7 8 9
1 1 2 3 4 5 6 7 8 9
2 2 4 6 8 10 12 14 16 18
3 3 6 9 12 15 18 21 24 27
4 4 8 12 16 20 24 28 32 36
5 5 10 15 20 25 30 35 40 45
6 6 12 18 24 30 36 42 48 54
7 7 14 21 28 35 42 49 56 63
8 8 16 24 32 40 48 56 64 72
9 9 18 27 36 45 54 63 72 81
Thats the end of chapter 4 - Iteration. From now on you should be rather comfortable with programming flows(conditional statements and iteration) and its logic. If you ever open a Mys php file, you will find that conditional statements and iterations are everywhere. Indeed, they are among the most powerful tools in PHP programming, you will have to at least understand how they work in order to proceed further. We will introduce another key concept - functions in next chapter.