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:

<?hh // strict

namespace Hack\UserDocumentation\Statements\Do\Examples\TableOfSquares;

<<__EntryPoint>>
function main(): void {
  $i = 1;
  do {
    echo "$i\t".($i * $i)."\n"; // output a table of squares
    ++$i;
  } while ($i <= 10);
}
Output
1	1
2	4
3	9
4	16
5	25
6	36
7	49
8	64
9	81
10	100

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.

See compound statements for a discussion about the use of braces around the statement body.