PHP for loop : Looping statement
In the previous chapter we have seen the if-else statement, elseif ladder and switch case statements. In this tutorial we will learn loop statement in php.
PHP for loop :
The for loop in PHP is used to execute some statement repetitively for a fixed number of times.Refer the following syntax of for loop -
for ( init; condition; increment ) { statement(s); }
Example of for loop :
<!DOCTYPE html> <html> <body> <?php for( $i=0; $i<5; $i++ ) { echo "Value of i : ". $i . "<br />"; } ?> </body> </html>
Output :
value of i : 0 value of i : 1 value of i : 2 value of i : 3 value of i : 4
Explanation of the program :
For loop comrpise of the three steps.
- In first step, the initial expression is evaluated. Initial value is provided to the loop index variable.
- In next step, the test-expression is evaluated. If the value is non-zero, the loop is executed and if the value is zero, the loop is terminated without execution.
- In the third step of the execution of for-loop, the update expression is evaluated.
PHP For loop flowchart :
Different forms of for loop -
In the following for loop note the semicolon at the end of for loop. Above for loop does not have any body.
<?php for( $i=0; $i<5; $i++ ); { echo "Value of i : ". $i; } ?>
above for loop is equivalent to -
for( $i=0; $i<5; $i++ ) {}