On the last page you learned how to make a block of code execute only when certain conditions are met. On this page you will learn how to make a block of code repeat execution until certain conditions are met. There are three different ways of making a loop; the While Statement, the Do ... While Statement and the For Statement. They each consist of a test and a block of code to execute while the test returns true. but the have different syntax which makes them behave differently.
The basic syntax of a while statement is:
The initializing statements will contain something that you will use in your test to determine if you will break out of the loop or not.
<?
$counter = 0;
while ( $counter <= 10 )
{ echo "5 times = $counter<br />";
$counter++;
}
?>
$counter
=
0
;
creates a variable to use as a counter and sets it to zero.
$counter
<=
10
tests if $counter is less than or equal to 10. If the test returns true, the block of code is executed then $counter is incremented and the loop return to the top to be tested again. If you forget to increment $counter, it will always equal zero and the loop will never end. When the test is not true, the loop is not executed. The code above outputs:
5 times 0 = 0
5 times 1 = 1
5 times 2 = 2
5 times 3 = 3
5 times 4 = 4
5 times 5 = 5
5 times 6 = 6
5 times 7 = 7
5 times 8 = 8
5 times 9 = 9
5 times 10 = 10
The do ... while statement looks like an up-side down do statement:
do {
Since the test take place after the code block, it will always be executed at least once. Note that unlike a for statement, you need a simicolon after the test.
# code to be executed
}
while ( test );
A for statement is just a short hand way of doing a while statement. The initialization, testing and incrementing of the counter variable is all done on one line. The basic syntax is:
for ( initialization; test; increment )
To multiply the numbers zero to 10 by two:
{ code block}
<?
for ( $counter=0; $counter<=10; $counter++ )
{
echo "$counter times 2 is " . $counter*2 . "<br />"; }
?>
|
|
|