What is the purpose of a while loop in PHP?

The while loop in PHP is an iteration structure used to repeatedly execute a block of code until a specified condition is no longer met. Its purpose is to repeat the execution of a specific code block as long as a given condition is met.

The basic syntax of a while loop statement is as follows:

while (condition) {
    // 要执行的代码块
}

Before each iteration, the condition is checked to see if it is true. If the condition is true, the code block is executed; then the condition is checked again. This process continues until the condition is no longer true, at which point the loop will be exited and the code following the loop will be executed.

For example, the following code snippet demonstrates using a while loop to calculate the sum of numbers from 1 to 10.

$sum = 0;
$i = 1;

while ($i <= 10) {
    $sum += $i;
    $i++;
}

echo "Sum is: " . $sum;  // 输出结果:Sum is: 55

In the above example, the while loop continuously increases the value of the variable $i and adds it to the variable $sum until $i is greater than 10, at which point the loop ends. Finally, the value of the variable $sum is output.

bannerAds