Statements: Do
The general format of a do
statement is
do
statement while (
expression );
The single statement is executed. If the expression tests true
, the process is repeated. If the expression tests false
, control transfers
to the point immediately following the end of the do
statement. The loop body (that is, the single statement) is executed one or more times.
Consider the following:
$i = 1;
do {
echo "$i\t".($i * $i)."\n"; // output a table of squares
++$i;
} while ($i <= 10);
The execution of a do
statement is impacted by a subordinate
break
or continue
.
The controlling expression must have type bool
or a type that can be converted implicitly to bool
. For example, in do
... while (1);
do
... while (123);
and do
... while (-1.234e24)
, in each case, the value of the expression is non-zero, which is implicitly converted
to true
. Only zero-values are converted to false
.
The do
statement behaves slightly differently than while
in that the former executes the loop body before it tests the controlling
expression, whereas while
executes it after.