Loops In PHP

Four types of loop in php:

  1. for
  2. foreach
  3. while
  4. do while

For Loop

Syntax 1:
for( Initialization ; Condition ; Increment/Decrement ){

Statement;

}
Example 1: Write a program to print value from 1 to 5.
<?php
for($initialization=1 ; $initialization<=5 ; $initialization++){
    echo $initialization."<br>";
}
?>
Output:
1
2
3
4
5

Syntax 2:
for( Initialization1 , Initalization2 ; Condition ;  Increment/Decrement ,  Increment/Decrement ){

Statement;

}
Example 2 : Write a program to print 1 to 5 as well as 5 to 1.
<?php
for($initialization1=1 , $initialization2 = 5; $initialization1<=5 ; $initialization1++ ,$initialization2-- ){
    echo $initialization1."&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;$initialization2<br>";
}
?>
Output:
1     5
2     4
3     3
4     2
5     1

Syntax 3 :
Initialization;
for ( ; Condition ; Increment/Decrement ){

Statement;

}

Syntax 4 :
Initialization;
for( ; Condition ; ){

Statement;
Increment/Decrement;

}

While Loop:

Syntax 1:

 while(condition true){

statement1;

}

Example 1 :

<?php
$var = 5;
while($var!=0){
echo $var;
$var--;
}
?>

Output : 54321
Note : While loop work if and only if while condition is true.

Do While Loop:

Syntax 1:

do{

statement1;

}while(condition true)

Note : Suppose you have a situation in which you would like to execute one statement without condition and the same statement with condition then in this type of situation "do while" conditional statement is useful.

Example 1:

<?php
$var = 5;
do{
/**
* This statement will execute first time without any condition
* but next time execute with while condition.
*/
echo "value = $var<br>";
$var--;
}while($var!=0);
?>

Output :
value = 5
value = 4
value = 3
value = 2
value = 1

One thought on “Loops In PHP”

Comments are closed.