Page 69 - Open Soource Technologies 304.indd
P. 69
Unit 3: Flow-Control Statements and PHP in Web Page
A do ... while statement is like a while statement in reverse. First it runs the block of code, then Notes
it evaluates the conditional expression. If the conditional expression is true, then it loops back to
the beginning of the statement and starts again.
It takes the form of:
do {
statements;
}
while (expression);
Note that since the curly brackets do not end the entire statement, we need a semicolon at the end.
$x = 0;
do {
$a =$ a + $b[$x];
$x++;
}
while ($x < 10);
This code will have the same effect as the equivalent while loop above. One that would work
differently might be as follows:
// will never run
// since the initial state of $x
// is $x != 10
$x = 0;
while ($x == 10) {
$a = $a + $b[$x];
$x++;
}
// will run once
// even though the initial state of $x
// is $x != 10
$x = 0;
do {
$a = $a + $b[$x];
$x++;
}
while ($x == 10);
LOVELY PROFESSIONAL UNIVERSITY 63