Page 70 - Open Soource Technologies 304.indd
P. 70
Web Technologies-I
Notes A more practical use for this loop might be to check whether something has a value. For instance,
you could walk an array as long as you keep finding values.
$x = 0;
do {
if ($aName[$x]) {
$bName[$x] = someProc($aName[$x]);
}
$x++;
}
while (isset($aName[$x]));
In the preceeding example, we take advantage of the fact that non-existent value return false.
This example assumes all the array elements are contiguous, since it will stop executing with the
first empty array element it finds.
The do ... while has no alternative syntax, partly since anything you can do with a do ... while
statement you can also do with a while statement. The do ... while is just easier to read in
certain circumstances. It is also partly because the while, in occurring at the end, would be
indistinguishable from a nested while loop if the curly brackets were omitted.
3.3.3 For Statement
The for statement allows for incremental processing based on some incremental variable.
Unlike the while statement, the variable is incremented within the conditional expression itself.
This means that you do not have to have code in the body of the statement to set the termination
condition. This does not mean that you cannot set the termination condition in the body, merely
that you do not have to.
Once again, the statement keeps executing as long as the conditional statement is true.
It takes the form of:
for (init; condition; increment) {
statements;
}
The three values that go inside the for statement conditional expression are:
init
The initial state of the variable to be tested. Normally done as an assignment, although the assigned
value can be from any source, literal or variable.
condition
The condition to be tested for. The statement keeps processing as long as it remains true.
increment
The increment by which the variable being tested changes.
64 LOVELY PROFESSIONAL UNIVERSITY