Categories
PHP

While, For, Foreach Loops

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.

With the help of loops, you can repeatedly run a PHP code-block until a specific condition occurs. Similar to if/else statements, if the given expression evaluates to true, the loop continues running, and when the expression evaluates to false, the loop stops running.

While Loop

The while loop is the simplest looping structure but sometimes the least compact to use. The while loop repeats one or more statements-the loop body-as long as a condition remains true. The condition is checked first, then the loop body is executed. So, the loop never executes if the condition isn’t initially true. Just as in the if statement, more than one statement can be placed in braces to form the loop body.

The following fragment illustrates the while statement by printing out the integers from 1 to 10 separated by a space character:

<?php
$counter = 1;
while ($counter < 11) {
  echo $counter. ' ';
  // Add one to $counter
  $counter++;
}
//1 2 3 4 5 6 7 8 9 10

Do…While Loop

The difference between while and do...while is the point at which the condition is checked. In do...while, the condition is checked after the loop body is executed. As long as the condition remains true, the loop body is repeated.

You can emulate the functionality of the while example as follows:

<?php
 $counter = 1;
 do {
  echo $counter . ' ';
  $counter++;
} while ($counter < 11);
//1 2 3 4 5 6 7 8 9 10

While vs. Do…While Loops

The contrast between while and do...while can be seen in the following example:

<?php
 $counter = 100;
 do {
  echo $counter;
  echo " ";
  $counter++;
} while ($counter < 11);
//100

This example outputs 100, because the body of the loop is executed once before the condition is evaluated as false.

The do...while loop is the least-frequently used loop construct, probably because executing a loop body once when a condition is false is an unusual requirement.

For Loop

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:

<?php
for($counter=1; $counter<11; $counter++) {
  echo $counter. ' ';
}
//1 2 3 4 5 6 7 8 9 10

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

<?php
/*for (
 1. initial statement;
 2. conditional expression;
 3. end loop statements
)*/

//      1.      2.    3.
for ($i = 1; $i < 11; $i++)
 echo $i . ' ';
//1 2 3 4 5 6 7 8 9 10
  1. Initial statements
    Statements that are executed once, before the loop body is executed.
  2. Loop conditions
    The conditional expression that evaluated before each execution of the loop body. If the conditional expression evaluates as false, the loop body is not executed.
  3. 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 that 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 statement 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:

<?php
for($x=0,$y=0; $x<10 && $y<$z; $x++,$y+=2){
 //your code
}

However, complex for loops can lead to confusing code.

Foreach Loop

The foreach statement 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 later.

Changing Loop Behavior

To break out of a loop early before the loop condition becomes false, the break statement is useful.

break

break ends execution of the current for, foreach, while, do-while or switch structure. It accepts an optional numeric argument that tells it how many nested enclosing structures are to be broken out of.

This example illustrates the idea:

<?php
$y = 10;
for($x = 1; $x < 100; $x++) {
  if ($x > $y)
    break;
  echo $x;
}
//1 2 3 4 5 6 7 8 9 10

If $x reaches 100, the loop terminates normally. However, if $x is (or becomes) greater than $y, the loop is terminated early, and program execution continues after the loop body. The break statement can be used with all loop types.

continue

continue is used within looping structures to skip the rest of the current loop iteration and continue execution at the condition evaluation and then the beginning of the next iteration.

To start again from the top of the loop without completing all the statements in the loop body, use the continue statement. Consider this example:

<?php
$x = 1;
$y = 10;
while($x < 100) {
  echo $x . ' ';
  $x++;
  if ($x > $y)
    continue;
  echo $y .' ';
}

The example prints and increments $x each time the loop body is executed. If $x is greater than $y, the loop is begun again from the top; otherwise, $y is printed, and the loop begins again normally. Like the break statement, continue can be used with any loop type.

For loop example: The list of odd numbers from 1 to 20:

<?php
for($i=1; $i <= 20; $i++){
 if ($i % 2 == 0)
  continue;
 echo $i . ' ';
}
//1 3 5 7 9 11 13 15 17 19

While loop example: The list of even numbers from 1 to 20

<?php
$i = 0;
while($i <= 20){
 $i++;
 if ($i % 2 != 0)
  continue;
 echo $i . ' ';
}
//2 4 6 8 10 12 14 16 18 20

PHP Control Structures:

  1. If elseif else and Switch Case Conditional Statements
  2. Conditional Expressions
  3. Ternary, Elvis, and Null Coalescing Operators
  4. Using Loops
  5. Using GOTO Operator