PHP Iteration Statements

By Kunal Kapoor
20-04-2018
545

There are three kinds of loops

  • for loop

for(initialization , condition , iteration){

}

 

In case of for loop, you can set a starting value, set a condition  and then you execute it.

For loop checks the condition of the loop in the beginning of execution.

  • while loop

while(condition){

}

 

In while loop, you can set a condition and loop will continue to endlessly execute until condition holds true.

While loop checks the condition before the loop execution

 

  • do while loop

do{

} while(condition);

 

Do while loop executes just like normal while loop, except that it checks the condition after the execution of loop.


example:


<?php

$x = 1;

// testing while loop

echo "<b>Testing while loop: </b><br>";
while($x<5){
echo "current iteration = ".$x."<br>";
$x++;
}

// testing do while loop
echo "<br>";
echo "<b>Testing do while loop:</b> <br>";
$x=1;
do{
echo "current iteration = ".$x."<br>";
$x++;
}while($x<5);



// testing dor loop
echo "<br>";
echo "<b>Testing for loop:</b> <br>";
for($x=1;$x<5;$x++){
echo "current iteration = ".$x."<br>";
}


?>


Output is as follows:

Testing while loop: 
current iteration = 1
current iteration = 2
current iteration = 3
current iteration = 4

Testing do while loop: 
current iteration = 1
current iteration = 2
current iteration = 3
current iteration = 4

Testing for loop: 
current iteration = 1
current iteration = 2
current iteration = 3
current iteration = 4



Related Tutorials