Prev | Current Page 176 | Next

W. Jason Gilmore

"Beginning PHP and MySQL: From Novice to Professional"


The while Statement
The while statement specifies a condition that must be met before execution of its
embedded code is terminated. Its syntax is the following:
while (expression) {
statements
}
In the following example, $count is initialized to the value 1. The value of $count is
then squared and output. The $count variable is then incremented by 1, and the loop
is repeated until the value of $count reaches 5.
$count = 1;
while ($count < 5) {
printf("%d squared = %d
", $count, pow($count, 2));
$count++;
}
?>
The output looks like this:
1 squared = 1
2 squared = 4
3 squared = 9
4 squared = 16
Like all other control structures, multiple conditional expressions may also be
embedded into the while statement. For instance, the following while block evaluates
either until it reaches the end-of-file or until five lines have been read and output:
CHAPTER 3 ?–  PHP BASICS 103
$linecount = 1;
$fh = fopen("sports.txt","r");
while (!feof($fh) && $linecount<=5) {
$line = fgets($fh, 4096);
echo $line. "
";
$linecount++;
}
?>
Given these conditionals, a maximum of five lines will be output from the sports.txt
file, regardless of its size.
The do...while Statement
The do...while looping statement is a variant of while but it verifies the loop conditional
at the conclusion of the block rather than at the beginning. The following is its
syntax:
do {
statements
} while (expression);
Both while and do.


Pages:
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188