home | O'Reilly's CD bookshelfs | FreeBSD | Linux | Cisco | Cisco Exam    

Web Database Applications with PHP \& MySQLWeb Database Applications with PHP \& MySQLSearch this book

2.3. Loops

Loops in PHP have the same syntax as other high-level programming languages.

Loops add control to scripts so that statements can be repeatedly executed as long as a conditional expression remains true. There are four loop statements in PHP: while, do...while, for, and foreach. The first three are general-purpose loop constructs, and foreach is used exclusively with arrays.

2.3.3. for

The for loop is the most complicated of the loop constructs, but it also leads to the most compact code.

Consider this fragment that implements the example used to illustrate while and do...while:

for($counter=1; $counter<11; $counter++)
{
  echo $counter;
  echo " ";
}

The for loop statement has three parts separated by semicolons, and all parts are optional:

Initial statements
Statements that are executed once, before the loop body is executed.

Loop conditions
The conditional expression that is evaluated before each execution of the loop body. If the conditional expression evaluates as false, the loop body is not executed.

End-loop statements
Statements that are executed each time after the loop body is executed.

The previous code fragment has the same output as our while and do...while loop count-to-10 examples. $counter=1 is an initial statement that is executed only once, before the loop body is executed. The loop condition is $counter<11, and this is checked each time before the loop body is executed; when the condition is no longer true—i.e., when $counter reaches 11—the loop is terminated. The end-loop statement $counter++ is executed each time after the loop body statements.

Our example is a typical for loop. The initial statements sets up a counter, the loop condition checks the counter, and the end-loop statement increments the counter. Most for loops used in PHP scripts have this format.

Conditions can be as complex as required, as in an if statement. Moreover, several initial and end-loop statements can be separated by commas. This allows for complexity:

for($x=0,$y=0; $x<10&&$y<$z; $x++,$y+=2)

However, complex for loops can lead to confusing code.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.











??????????????@Mail.ru