• Home
  • How do I run a while loop in PHP?

How do I run a while loop in PHP?

To run a while loop in PHP, you can use the following syntax:

while (condition) {
// code to be executed
}

The condition is evaluated at the beginning of each iteration of the loop. If the condition is true, the code inside the loop is executed. If the condition is false, the loop ends.

Here is an example of a simple while loop that counts from 1 to 10:

$i = 1;
while ($i <= 10) {
echo $i . "\n";
$i++;
}

This loop will output the numbers 1 through 10, each on a new line. The variable $i is incremented by 1 at the end of each iteration, so that the loop eventually ends when $i becomes greater than 10.

You can also use the break statement to exit the loop early, or the continue statement to skip the rest of the current iteration and move on to the next one.