Loop statements in PHP with examples

PHP loop articulations: In this article, we will find out about the different loop proclamations in PHP programming language with examples.

Loops

Envision that we need a program that says “hi world” multiple times. It’s very distressing and exhausting to compose the announcement – reverberation “hi world” — multiple times in PHP. This is the place loop proclamation encourages the work for us.

A loop proclamation is an explanation that executes up to a specific condition is legitimate and stops when that condition is invalid.

We should take a gander at the various loops in PHP.

1) The while loop

The while proclamation executes a specific square of code up to an announcement stays genuine.

Syntax:

    while (condition true) {
         code to be executed;
    }

Example:

We need to show the number 1 to 5.

<?php
$x = 1;
while ($x <= 5) {
    echo "Number is: $x <br>";
    $x++;
}
?>

Output:

Number is :1
Number is :2
Number is :3
Number is :4
Number is :5

2) The do…while loop

The do…while loop is equivalent to the while loop however for that it executes your code at least once regardless of whether the condition is bogus before checking the condition to genuine and keeps executing as the announcement stays genuine.

Syntax:

    do {
        code to be executed;
    } while (condition is true);

Example:

In this example, we will rehash the example above however show how the to-do..while loop executes your code at least once whether genuine or bogus before checking the condition.

<?php
$x = 1;
do {
    echo "Number is: $x <br>";
    $x++;
} while ($x >= 5);
?>

Output:

Number is :1

3) The for loop

The for loop fills in as the while loop however a distinction in syntax, in this loop every one of the things like counter instatement, condition, augmentation and decrement explanations are set together isolated by the semicolon.

Syntax:

    for (initialization counter; test counter; increment/decrement  counter) {
        code to be executed;
    }

The introduction counter is utilized to set the underlying value.

Test counter or condition decides the execution procedure, if genuine the loop proceeds if false the loop stops.

The addition/decrement counter used to augmentations or decrements the underlying value.

Example:

<?php
for ($x = 1;$x <= 5;$x++) {
    echo "Number is: $x <br>";
}
?>

Output:

Number is :1
Number is :2
Number is :3
Number is :4
Number is :5

We go with our example again posting numbers from 1 to 5 with the for loop

Leave a Comment

error: Alert: Content is protected!!