Loops are used to execute the same block of code again and again, until a certain condition is true. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort.
PHP supports following four loop types.
The while statement will execute a block of code again and again if test expression is true.
If the test expression is true then the code block will be executed. After the code has executed the test expression will again be evaluated and the loop will continue until the test expression is found to be false.
Syntax of while loop
while (condition) { code to be executed; }
Syntax of while loop
This example increments a variable value on each iteration of the loop and the counter increments until it reaches 10 when the evaluation is false and the loop ends.
<?php $i = 0; while( $i < 10) { echo $i."<br>"; $i++; } ?>
The do…while statement will execute a block of code at least once – then if condition is true then block of code will be execute.
Syntax of do…while
do { code to be executed; } while (condition);
The Example do…while loop statement
The following example will increment the value of i at least once, and it will continue incrementing the variable i until value of i less than 10.
<?php $i = 0; do { echo $i."<br>"; $i++; } while( $i < 10 ); ?>
The for statement is used when you know how many times you want to execute a statement or a block of statements.
Syntax of loop statement
for (initialization; condition; increment){ code to be executed; }
The initializer is used to set the start value for the counter of the number of loop iterations. A variable may be declared here for this purpose and it is traditional to name it $i.
second is condition here we set the condition and then set the increment and decrements.
Example of loop statement
The following example makes simple iterations and increment the value of $i variable.
<?php for( $i = 0; $i<5; $i++ ) { echo $i."<br>"; } ?>
This is the special loop in PHP. The foreach statement is used to loop through arrays. For each pass the value of the current array element is assigned to $value and the array pointer is moved by one and in the next pass next element will be processed.
Syntax of foreach loop statement
foreach (array as value) { code to be executed; }
Example of foreach loop statement
Try out following example to list out the values of an array.
<?php $array = array( 1, 2, 3, 4, 5); foreach( $array as $value ) { echo "Value is $value <br />"; } ?>