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

';
        $i++;
    }
?>




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

';
        $n++;
    }
    while($n <= 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

';
    }
?>


Practice Exercises