Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

Write a program code for do-while Statement in PHP.

Explain do-while statement in PHP with an example.

In PHP, we can use the do-while loop to execute a block of code at least once, and then repeatedly as long as a certain condition is true.

The syntax of the do-while loop is as follows:

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

Here, condition is the condition that we want to check. The code inside the loop will be executed at least once, and then repeatedly as long as the condition is true.

Here’s an example that demonstrates how to use a do-while loop in PHP:

<?php

$i = 1;
do {
    echo $i . "<br>";
    $i++;
} while ($i <= 10);

?>

Explanation:

In this code, we define a variable $i with a value of 1. We then use a do-while loop to output the value of $i and increment it by 1 on each iteration. The loop continues to execute as long as $i is less than or equal to 10.

When we run this code, it will output the numbers 1 to 10 on separate lines.

The do-while loop is similar to the while loop, but it guarantees that the code inside the loop will be executed at least once, regardless of whether the condition is true or false. It is useful when we need to execute a block of code at least once, and then repeatedly as long as a certain condition is true.