A PHP while loop is a control structure that repeatedly executes a block of code as long as a specified condition remains true. It checks the condition before each iteration and continues execution until the condition evaluates to false.
PHP While loop
Basic Syntax of While Loop
The basic syntax of "While" Loop in PHP is as follows:
while (condition) {
// Code to be executed as long as the condition is true
}
- while: The keyword that signifies the start of the while loop.
- condition: The condition to be evaluated before each iteration. If this condition is true, the code inside the loop will execute. If it's false initially, the loop won't run at all.
- {}: The curly braces define the block of code that will be executed repeatedly as long as the condition remains true.
Counting from 1 to 5
$num = 1;
while ($num <= 5) {
echo $num . " ";
$num++;
}
- We initialize the variable $num to 1.
- The while loop checks if $num is less than or equal to 5 before each iteration.
- If the condition is true, it executes the code inside the loop, which includes printing the value of $num and incrementing it by 1.
- The loop continues until $num is no longer less than or equal to 5. In this example, it prints "1 2 3 4 5 ".
User Input Validation
$valid = false;
while (!$valid) {
$userInput = readline("Enter a valid number: ");
if (is_numeric($userInput)) {
$valid = true;
} else {
echo "Invalid input. Please enter a valid number.\n";
}
}
echo "You entered a valid number: " . $userInput;
- Here, we use a while loop to repeatedly prompt the user for input until they enter a valid number.
- Initially, the $valid variable is set to false.
- The loop continues as long as $valid is false.
- Inside the loop, we use readline() to get user input, check if it's numeric using is_numeric(), and set $valid to true if the input is valid.
- If the input is invalid, an error message is displayed, and the loop continues.
Calculating Factorial
$n = 5;
$factorial = 1;
while ($n > 0) {
$factorial *= $n;
$n--;
}
echo "Factorial of 5 is: " . $factorial;
- In this example, we calculate the factorial of 5 using a while loop.
- The loop continues as long as $n is greater than 0.
- In each iteration, we multiply the current value of $factorial by $n and then decrement $n.
- The loop continues until $n becomes 0, resulting in the factorial of 5.
These examples illustrate how PHP while loops can be used for tasks such as counting, user input validation, and mathematical calculations. The loop continues executing until the specified condition becomes false, allowing you to control repetitive tasks in your PHP programs.
×