Looping statements help us to run a piece of code again and again. For example, you want to show 1 to 100 on your page. In normal cases, you have to write echo 100 times with the number to show 1 to 100 on the web page. But with the help of a loop, you can do this task very easily by writing an echo only once. There are three looping statements in PHP.
Page Contents
- for loop
- while loop
- do-while loop
Now we will learn each looping statement in detail.
For loop: –
for loop is used to run a piece of code for a certain number of times. For loop take three expressions. In the first expression, we initialize a variable after that in the second expression we write and condition, and in the last expression we increment or decrement the variable. To understand it you can check the following syntax to define for loop in C.
for (initializationStatement; testExpression; updateStatement)
{
// statements inside the body of for loop
}
Check this example. In this example, we will write 1 to 10 using for loop.
Example Program:
<?php
for($i=1;$<=10;$i++){
echo "$i\n";
}
?>
While loop: –
If you want to run a piece of code again and again until a certain condition is true. You can use a while loop. while loop takes only a single expression which is a conditional expression. Check out the syntax to define a while loop in PHP.
while(condition){
//body of the loop
}
Here is an example of a while loop.
Example Program: –
<?php
$i=1;
while(i<=10){
echo "$i\n";
$i++;
}
?>
Do while loop: –
The do-while loop is the same as the while loop but there is a small difference. In case of the false condition in the first iteration of the while loop, the Body of the while loop would not run. But in the case of the do-while loop. It will run. because it checks the condition after running the body of the loop. Check out the syntax to define the do-while loop in PHP.
do{
//body of the loop
}while(condition)
Example Program: –
<?php
$i=1;
do{
echo "Hello";
}while(i!=1)
?>