There are not many loops that we cannot code with "foreach" and must use "while" instead. However, using a "while" with a condition looks more natural to most programmers than using a foreach loop starting with an if-break statement.
For example, we can do database operation as in the foreach example:
database prod query="select * from Product";
var prodrec = "(db)prod";
while ({#prodrec} > 0 && '{status%database}' == 0) {
if ('{prodrec:Price}' != 0) {
display "Product {result%while:iteration}: "; display "{prodrec:Name} ({prodrec:Code}) costs ";
display "{prodrec:Price} per {prodrec:Unit}<br>\n";
}
var prodrec = "(db)prod";
}
Please note that retrieving beyond the last record in the record set does not generate an error. That is why we need to check the size of the retrieved record to determine if the end of record set is reached. Also, because the "while" loop check-first-before-run, you need to fetch-ahead the first record before the loop starts, and fetch subsequent record at the end of the loop before the next iteration.
Same as in "foreach" loop, to prevent an accidental endless "while" loop, "maxiter" is default to 1000. If you want the loop to go until the end regardless, set maxiter to 0.
while (true) display "{result%while:iteration}\n";
The above will display a sequence of numbers from 1 to 1000. Unlike in "foreach", empty bracket in a "while" condition is not allowed. At least a dummy condition (true) is required.
The choice between using "while" or "foreach" depends on team culture (or "religion" if you happens to be the team leader, or "standard" if you happens to be the manager.) There are little differences (if any) in performance as they are both implemented as "while" loop internally.
|