PHP While – Do While Loop
The While Loop is used to repeat executing a certain code as long as a given condition is (still) true.
while( … condition … ) {
… execute code …
}
The code between accolades is only executed when the condition between brackets is true ( just like the If Loop) however after it executed the code, it will go back to check the condition again; if it’s still true, it will execute the code again, etc.. This will be repeated until the condition between brackets is no longer true. Only then, it will stop executing the code and continue with the rest of your script ( below the while loop ). Therefore, you should watch out for endless while loops ( which keep repeating themselves for an infinitive time ), for ex.:
$num = 1;
while($num == 1) {
echo “Num equals 1.”;
}
As num is always equal to 1, this code will be executed forever. When that happens, the rest of your script is no longer executed and the browser will be stuck in executing the while loop script which will cause the browser to crash ( mostly ). A valid example of the use of a while loop could be for ex.:
$num = 1;
while($num <= 10) {
echo “<p>”.$num.”</p>”;
$num++;
}
Which shows the value of $num as long as it’s not greater than 10 and then increases it by 1. In other words: it counts to 10.
Now, another form of the while loop is the do while loop. The difference with the while loop is that the code of the do while loop is atleast executed ONCE ( no matter if the condition is true or not ). For example:
$num = 1;
do {
echo “<p>”.$num.”</p>”;
$num++;
}while($num <= 0);
Will result in displaying the number 1. However when we’d use the while loop instead, it would result in displaying nothing. The code would not be executed because the variable $num equals 1, which is greater than 0. The condition is false so the code won’t be executed ( not once ) in a while loop. However in a do while loop it executes it at least once but also after that it will check the condition and no longer execute the code when this condition is false.