[Previous] [Contents] [Next]

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.

foreach

The foreach statement was introduced in PHP4 and provides a convenient way to iterate through the values of an array. Like a for loop, the foreach statement executes the loop body once for each value in an array. The following code fragment converts an array of centimeter values to inches for each value in the array:

// Construct an array of integers
$lengths = array(0, 107, 202, 400, 475);

// Convert an array of centimeter lengths to inches
foreach($lengths as $cm)
{
  $inch = (100 * $cm) / 2.45;

  //or use the following calculation
  //$inch = 0.393700787 * $cm;

  echo "$cm centimeters = $inch inches\n";
}

The foreach loop is an extremely useful and convenient method of processing arrays and is discussed in detail in next section.

[Previous] [Contents] [Next]