PHP : while Loop

In PHP, the while loop is used to execute a block of code repeatedly as long as a specified condition is true. The condition is evaluated before each iteration of the loop, and if it evaluates to true, the loop body is executed. If the condition evaluates to false, the loop terminates, and the program continues with the code following the loop. Here's the basic syntax of the while loop:


while (condition) {
    // Code to be executed while condition is true
}
 

  • condition: An expression that is evaluated before each iteration. If it evaluates to true, the loop continues; otherwise, it terminates.
  • Example:


$i = 1;
while ($i <= 5) {
    echo "The value of i is: $i <br>";
    $i++;
}

 

In this example, the loop starts with the variable $i initialized to 1. The loop continues executing as long as $i is less than or equal to 5. Inside the loop body, it prints the value of $i and increments $i by 1 in each iteration.

The output of the above code will be:


The value of i is: 1
The value of i is: 2
The value of i is: 3
The value of i is: 4
The value of i is: 5

 

It's important to ensure that the condition within a while loop eventually becomes false to prevent an infinite loop. Otherwise, the loop will continue indefinitely, and your program may become unresponsive.