Php – While and Do While Loops – POFTUT

Php – While and Do While Loops


[rps-include post=6522]

In previous chapter we have looked for and foreach loops. In this chapter we will look another Php programming language loop while and do while loops.

While Loop

while loop iterates over given code block unless the condition met. The condition is checked in before every step. If the condition do not meet the while loop will end. Syntax is like below.

while(CONDITION){
CODE
}
  • CONDITION is checked after every step
  • CODE will run in every step

In this example we will count from 1 to 10 and use variable named $counter and increase it in every step.

$counter = 1;

while($counter<=10){

    echo $counter;

    $counter++;

}

If we run code above we will get following output. The name of the code file is index3.php

$ php index3.php

Do While Loop

Do while is very same with while but the sequence is reverse. First the CODE block is executed and then the CONDITION is checked. Syntax is like below.

do{

CODE

} while (CONDITION)

In this example we will do same of previous example.

$counter = 1; 
 
do{ 
    echo $counter."\n"; 
 
    $counter++; 
 
}while($counter<=10)

[rps-include post=6522]

LEARN MORE  C For Loop and Iteration

Leave a Comment