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.
PHP Do-While loop
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;
- In this example, we use a do-while loop to repeatedly prompt the user for input until they enter a valid number.
- The $valid variable is initially set to false.
- The code inside the loop block asks the user for input using readline(), checks if it's numeric using is_numeric(), and sets $valid to true if the input is valid.
- If the input is invalid, an error message is displayed, and the loop continues.
- The loop continues executing until $valid becomes true, ensuring the user enters a valid number.
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!";
- Here, we simulate rolling a die until we get a 6 using a do-while loop.
- The $roll variable is initialized to 0.
- Inside the loop, we use rand(1, 6) to generate a random number between 1 and 6, simulating a die roll.
- The loop continues until $roll is equal to 6, and it displays each roll along the way.
- Once a 6 is rolled, the loop exits, and it displays "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=>;
- In this example, we calculate the sum of numbers from 1 to 10 using a do-while loop.
- We initialize $n to 1 and $sum to 0.
- Inside the loop, we add the current value of $n to $sum and increment $n by 1 in each iteration.
- The loop continues until $n is no longer less than or equal to 10, resulting in the sum of numbers from 1 to 10.
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.
×