Using loop Statements


In addition to conditional statements like if/else and switch, PHP also supports loops.

Looping with the for loop

The for loop, which repeatedly executes a statement, looks like this in PHP:

 for (expression1; expression2; expression3)   statement 

Here, as in JavaScript, expression1 lets you initialize your loop, often by initializing a loop counter, also called a loop index, that tracks how many times the loop has executed. The next expression, expression2, is the test expression; the loop keeps going while this expression remains true. You usually test the value in your loop counter here. The final expression, expression3, is executed after the loop is executed, each time through the loop. You usually increment your loop counter variable in that expression. Every time through the loop, statement, which can be a compound statement consisting of many single statements enclosed in curly braces, is executed.

Here’s an example, for.php. In this example, the code uses a for loop to display a line of text six times. The loop starts by setting a loop counter variable named $loop_counter to 0, incrementing it each time after the loop runs, and testing to make sure the loop counter doesn’t exceed 6:

 <html>     <head>         <title>             Using the for loop         </title>     </head>     <body>         <h1>             Using the for loop         </h1>         <?            for ($loop_counter = 0; $loop_counter < 6;              $loop_counter++){              .              .              .            }         ?>     </body> </html>

Then you add the body of the loop, which is what displays the text in the Web page:

 <html>    <head>        <title>            Using the for loop        </title>    </head>    <body>        <h1>            Using the for loop        </h1>        <?            for ($loop_counter = 0; $loop_counter < 6;              $loop_counter++){              echo "You're going to see this six times.<BR>";            }        ?>    </body> </html>

The results of this code appear in Figure 12.13, where, as you can see, the text was displayed six times.

image from book
Figure 12.13: Using the for loop



Ajax Bible
Ajax Bible
ISBN: 0470102632
EAN: 2147483647
Year: 2004
Pages: 169

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net