In PHP programming, we are often required to repeat a block of code, instead of adding several almost equal lines in a script we can use loops to perform a task like this. PHP has three types of loop constructs that all do the same thing, repeat a block of code a number of times, FOR loop, DO loop and WHILE loop. There are other types that have specific function in array : FOREACH. With FOREACH, it will loops through a block of code for each element in an array.

The FOR loop provides a compact way to create a loop with a specified number of times. We use the FOR loop when we know in advance how many times a block of code should run or execute. The FOR loop is also known as definite loop and it’s preferred by most programmers because it’s more convenient to use. See following example performs the FOR loop.

1
2
3
4
5
6
7
8
9
10
 
	/*
		for (initialization; condition; increment){
                              code needed to loop;
                       }
	*/
 
	For ($i=0; $i=10; $i++) {
		Print “number of counter : $i <br>;
          }

The FOR looping statement has three parts as arguments and separated by semicolons(;). The first part is an expression that is evaluated once when the loop begins. The second part is the condition, while the condition is true, the loop continues repeating. The third part is an expression that is evaluated once at the end of each pass of the loop.

The WHILE loop we use when we want a block of code to run while condition is true. The idea of the WHILE loop is do something over and over again until the task has been completed.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
	/*
 
while (condition) {
                      code needed to loop;
            }
 
             */
 
$i = 0;
while ($i <= 10){
    Print “number of counter : $i <br>;
$i++;
}

The DO loop is almost the same as the WHILE loop except that it executes the code at least one before condition is checked. The reason for this is that the condition statement is written at the end. So, the DO loop statement will always execute the block of code one, it will then check the condition and repeat the loop while the condition is true.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
 
	/*
do
  	{
  		code to be executed;
 	}
       while (condition);
		*/
 
		$i=0;
		do {
			$i++;
		Print “number of counter : $i <br>;
	} while ($i<=10);
Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Netvouz
  • DZone
  • ThisNext
  • MisterWong
  • Wists
  • Slashdot
  • Technorati
  • YahooMyWeb