do...while Loops in PHP

By: Andi, Stig and Derick Emailed: 1785 times Printed: 2623 times    

do

statement

while (expr);

The do...while loop is similar to the previous while loop, except that the truth expression is checked at the end of each iteration instead of at the beginning. This means that the loop always runs at least once.

do...while loops are often used as an elegant solution for easily breaking out of a code block if a certain condition is met. Consider the following example:

do {

statement list

if ($error) {

break;

}

statement list

} while (false);

Because do...while loops always iterate at least one time, the statements inside the loop are executed once, and only once. The truth expression is always false. However, inside the loop body, you can use the break statement to stop the execution of the statements at any point, which is convenient. Of course, do...while loops are also often used for regular iterating purposes.

Most Viewed Articles (in PHP )

Latest Articles (in PHP)

Comment on this tutorial