start learning
Image 1
5595

PHP Do-While loop

A PHP do-while loop is a control structure used to repeatedly execute a block of code as long as a specified condition remains true. Unlike the regular while loop, the do-while loop guarantees that the code block will be executed at least once, even if the condition is initially false.


Basic Syntax of Do-While Loop

The basic syntax of "Do-While" Loop in PHP is as follows:


do {
   // Code to be executed at least once
} while (condition);
 


User Input Validation


$valid = false;
do {
    $userInput = readline("Enter a valid number: ");
    if (is_numeric($userInput)) {
        $valid = true;
    } else {
        echo "Invalid input. Please enter a valid number.\n";
    }
} while (!$valid);

echo "You entered a valid number: " . $userInput;
 


Rolling a Die until You Get a 6


$roll = 0;

do {
    $roll = rand(1, 6);
    echo "Rolled a $roll.\n";
} while ($roll != 6);

echo "You rolled a 6!";
 


Calculating the Sum of Numbers from 1 to 10


$n = 1;
$sum = 0;

do {
    $sum += $n;
    $n++;
} while ($n <= 10);

echo "Sum of numbers from 1 to 10: " . $sum;
 


These examples illustrate how PHP do-while loops work and how they can be used for tasks such as user input validation, simulations, and calculations. The key difference from a regular while loop is that the code block is guaranteed to execute at least once.


×