What is the usage of a PHP while loop statement?
The while loop in PHP is used to repeatedly execute a block of code until a specified condition is no longer met. Its syntax is:
while (condition) {
// code to be executed
}
In this case, “condition” is an expression that, when its value is true, the loop will continue to execute; when its value is false, the loop will stop executing.
The code block within the loop will be repeatedly executed until the given condition is no longer met. Before each loop iteration, the condition will be checked. If the condition is true, the code within the loop body will be executed; if the condition is false, the loop body will be skipped, and the subsequent code will continue to execute.
When executing the code within the loop body, the loop counter can be manipulated as needed to control the number of iterations and behavior of the loop.
Here is an example demonstrating the use of a while loop to print numbers from 1 to 10.
$i = 1;
while ($i <= 10) {
echo $i . "<br>";
$i++;
}
In the example above, $i is the loop counter with an initial value of 1. The loop will continue running until the value of $i is greater than 10. Each iteration will output the current value of $i and increment $i by 1. The final output will be numbers from 1 to 10.