New course! Every coder should learn Generative AI!
Try a free lesson+ 2
While loop:
while (condition) {
excecute this code while the condition is true
}
$i = 1;
while ($i < 6) {
echo "i = $i<br>";
$i++;
}
Do while loop:
do {
excecute this code while the condition is true
this code will run at least once because the condition is checked at the end of the loop
} while (condition);
$i = 1;
do {
echo "i = $i<br>";
$i++;
} while ($i < 6);
For loop:
for (initialization; test; increment) {
code to excecute while test is true
}
for ($i = 1; $i < 6; $i++) {
echo "i = $i<br>";
}
All three examples should do the same thing here (print values from 1 to 5). If the condition wasn't matched the first time, the do while example would still print the value of i once before exiting the loop.