DJ Mike's Tutorials: PHP


< ^ >

Loops

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.


While Statements

The basic syntax of a while statement is:

Initializing statements
while ( test )
{ code block }


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


Do ... While Statements

The do ... while statement looks like an up-side down do statement:

do {
   # code to be executed
   }
while ( test );

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.

For Statements

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 )
{ code block}

To multiply the numbers zero to 10 by two:



<?
for ( $counter=0$counter<=10$counter++ )

echo 
"$counter times 2 is " $counter*"<br />"; }
?>




< ^ >


Created by DJ Mike from Santa Barbara

DJ Mike


Dance Away Santa Barbara's Home Page
<a href="http://www.statcounter.com/" target="_blank"> <img src="http://c5.statcounter.com/counter.php?sc_project=1321035&java=0&security=da2193dc" alt="counter free hit invisible" border="0" /></a>