Page 68 - Open Soource Technologies 304.indd
P. 68
Web Technologies-I
Notes 3.3.1 While Statement
The while statement is the most basic of iterative control structures. It repeatedly runs a block
of code until some condition is no longer true. If the condition is not true to begin with, then the
code never runs. It takes the form of:
while (expression) {
statements;
}
If we wanted to add together the first ten values from an array:
$x = 0;
while ($x < 10) {
$a = $a + $b[$x];
$x++;
}
In the above code, we initialize a variable to zero (0) before beginning the loop. The while statement
then evaluates the conditional expression. This expression must be inside parentheses. In this
case , zero is less than 10, so the statement executes.
The last line in the statement block increments the variable we are testing in our conditional
expression. In the body of a while statement there must be some code that changes the value of
the condition. Otherwise the loop will never terminate. In the following code, the conditional
expression will never become false, so the code will run forever (or until it crashes).
// bad code an infinite loop
$x = 0;
$z = 0;
while ($x < 10) {
$a = $a + $b[$z];
$z++;
}
This state of endless execution is known as an infinite loop. Anyone with any programming
experience is all too familiar with them. Their causes are many, and they are far too easy to create.
Like the if and switch statements from other, while has an alternative label based syntax.
while (expression):
statements;
endwhile;
3.3.2 Do ... while Statement
A while statement will never execute if its conditional expression never evaluates to true. What
happens if you want the code to always run at least once, regardless of the value of its conditional
expression?
The answer is use a do ... while statement.
62 LOVELY PROFESSIONAL UNIVERSITY