start learning
Image 1
50000050005

PHP While loop

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.


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
}
 


Counting from 1 to 5


$num = 1;

while ($num <= 5) {
    echo $num . " ";
    $num++;
}
 


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;
 


Calculating Factorial


$n = 5;
$factorial = 1;
while ($n > 0) {
    $factorial *= $n;
    $n--;
}
echo "Factorial of 5 is: " . $factorial;
 


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.