![]() |
|
PHP while and do while Loops. Free online PHP and MySQL Web Database Programming Tutorial... |
| Lessons | PHP do...while Loop |
|
|
In PHP we have the following looping constructs available: •while - loops through a block of code as long as a specified condition is true. •do...while - loops through a block of code once, and then repeats the loop as long as a specified condition is true. •for - loops through a block of code a specified number of times. •foreach - loops through a block of code for each element in an array. The while Loop The while statement executes a block of code as long as a specified condition is true. Its syntax follows: while (condition) code to be executed; Example The following example demonstrates a loop that continues to run as long as the variable i is less than, or equal to 10. Note that the variable i is incremented by 1 on each iteration of the while loop: <html> <body> <?php $i=1; while($i<=10) { echo "The number is " . $i . "<br />"; $i++; } ?> </body> </html> The do...while Statement The do...while statement in PHP is very similar to the while statement. There is just one difference being that the do...while loop is guaranteed to execute at least once no matter the loop condition is true or false. This is because in case of a while loop the condition is evaluated before every iteration, on the contrary in the case of a do...while loop the loop condition is evaluated after every iteration. The syntax of a do...while loop follows: do { code to be executed; } while (condition);
Next: PHP For Loop
|