PHP 8 Loop Control Structures

With loop control statements, you can more than once execute a block of code. It executes the sequence of statements many times until the stated condition becomes false. The control conditions should be well defined and determined otherwise the loop will execute an endless number of times.

These are the three loop control structures -

While loop in PHP

A while loop is the most straightforward looping structure. 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 in PHP

A 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. After the body is executed, then it checks the condition. If the condition is true, then it will again execute the body of a loop otherwise control is transferred out of the loop.

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 PHP

A for loop is a more efficient loop structure in programming language. 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;
}

The truth expression is a boolean expression that tests and compares the counter to a fixed value after each iteration and halting the for loop when false is returned. The incrementation/decrementation increases (or decreases) the counter by a set value.

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