Do While
The do...while loop in PHP is similar to the while loop, but it guarantees that the code inside the loop will be executed at least once, even if the condition is not met.
Here is the general syntax for a do...while loop in PHP:
do {
code to be executed;
} while (condition);
The code inside the loop is executed first, and then the condition expression is evaluated. If the condition is true, the loop continues to run. If the condition is false, the loop exits and the code after the loop is executed.
Here is an example of a do...while loop that counts from 1 to 10:
$i = 1;
do {
echo "$i ";
$i++;
} while ($i <= 10);
In this example, the value of $i is initialized to 1 before the loop starts. The code inside the loop will be executed at least once, regardless of the value of $i. At the end of each iteration, $i is incremented by 1. The loop will continue to run as long as $i is less than or equal to 10. 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 do...while loops to create a loop within a loop. Here is an example of a nested do...while loop that counts from 1 to 3 in the outer loop, and from 4 to 6 in the inner loop:
$i = 1;
do {
$j = 4;
do {
echo "$i, $j ";
$j++;
} while ($j <= 6);
$i++;
} while ($i <= 3);
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.