PHP 7 Loop Control Structures

These are the three loop control structures -

while loop

While loop is used for iteration. In each iteration, it evaluates the truth expression just like the If statement. If the condition evaluates to true, then the statement inside the loop is executed and control goes to the next iteration. If the condition evaluates to false, then the loop ends and control goes out of the loop.

Syntax of while Loop

while(condition){
    statements;
}

Example

<?php
    $i = 1;
    while($i < 6){
        echo 'The number is '.$i.'<br/>';
        $i++;
    }
?>

Output

The number is 1
The number is 2
The number is 3
The number is 4
The number is 5




do-while loop

do while loop is almost similar to the while loop except that the loop statement is executed at least once. In this, the conditional check is written at the end of the loop iteration. So the statement is executed first before the condition is tested.

Syntax of the do while loop

do {
    statements
}
while(condition);

Example

<?php
    $n = 0;
    do{
        echo 'Number is '.$n.'<br/>';
        $n++;
    }
    while($n <= 5)
?>

Output

Number is 0
Number is 1
Number is 2
Number is 3
Number is 4
Number is 5

for loop

In for loop, we have passed three parameters, initialize, truth expression and increment expression.

Syntax of the for loop

for(initialization; truth expression; increment expression){
    statements;
}

Example

<?php
    for($x =1; $x < 10; $x++){
        echo 'Number is '.$x.'<br/>';
    }
?>

Output

Number is 1
Number is 2
Number is 3
Number is 4
Number is 5
Number is 6
Number is 7
Number is 8
Number is 9


Practice Exercises





Read more articles


General Knowledge



Learn Popular Language