While
The while loop in PHP allows you to execute a block of code repeatedly as long as a given condition is true.
Here is the general syntax for a while loop in PHP:
while (condition) {
code to be executed;
}
The condition expression is evaluated at the beginning of each iteration, and the loop continues to run as long as the condition is true.
Here is an example of a while loop that counts from 1 to 10:
$i = 1;
while ($i <= 10) {
echo "$i ";
$i++;
}
In this example, the value of $i is initialized to 1 before the loop starts. The loop will continue to run as long as $i is less than or equal to 10. At the end of each iteration, $i is incremented by 1. The code inside the loop will print the value of $i on each iteration.
It is important to include a way to update the condition within the loop, or the loop will become an infinite loop and will continue to run indefinitely.
You can also nest while loops to create a loop within a loop. Here is an example of a nested while loop that counts from 1 to 3 in the outer loop, and from 4 to 6 in the inner loop:
$i = 1;
while ($i <= 3) {
$j = 4;
while ($j <= 6) {
echo "$i, $j ";
$j++;
}
$i++;
}
In this example, the inner loop will execute 3 times for each iteration of the outer loop, resulting in a total of 9 iterations. The code inside the inner loop will print the values of $i and $j on each iteration.