Phpdynamic

PHP and MySQL Programming Guides, Tutorials, & Articles

PHP Control Structures

PHP Control Structures

MAR 31

Repeating Statements with Loops

Throughout our daily routines we repeat certain actions over and over again to accomplish a task. A very basic example would be the steps we take when brushing our teeth (brush, rinse, gargle) and repeat these steps until we are satisfied with the results. We can apply this same analogy to a loop construct, which is used to execute a statement or block of statements repeatedly until a condition is satisfied. Since computers are very good at repeating operations, we can use loops to perform repetitive tasks that would otherwise be very time consuming and boring.

Similar to other programming languages PHP offers two types of loops: conditional loops, which are repeated an indefinite number of times until a condition is met and iterated or counter loops, which are repeated a fixed number of times.

The While Loop

A While loop is a perfect example of a conditional loop. It is used to execute statements over and over again as long as a condition is true. Of course you don’t want the loop to repeat forever, so at one point the condition has to evaluate to false. Otherwise it would be an infinite loop and you wouldn’t want that. Here is the syntax template for the While loop:

while ( condition ) {
...  // do this while condition is true
}

The While loop functions in the following way:

  • When the interpreter first encounters the While loop, it evaluates the condition enclosed by the parentheses.
  • If the condition is false, the interpreter skips the loop and code block following the loop.
  • If the condition is true, all the statements within the { } braces are executed and the loop condition is tested again.
  • If the condition is still true the execution of the statements is repeated.
  • The loop will keep iterating unless something in the code block causes the condition to become false at some point.

Here is an example of a While loop:

$a = 1;

while ( $a < 4 ) {
  print ($a);
  print ('<br>');
  $a++;
}

The output:

1
2
3

In the example above, if we omitted the $a++ statement from the code block, the loop condition will always be true and the loop will repeat over and over without end, which is called an infinite loop. Just make sure at one point the condition in the loop becomes false by one of the statements in the loop code block.

The For Loop

The For loop is used when you want something repeated a fixed number of times. Lets look at the syntax template followed by an example.

for ( expression1; condition; expression2 ) {
   ...// do this until condition is false
}

The code block after the For loop statement is repeated a certain number of times. expression1 is only executed once, it is used to set an initial counter variable. The condition statement is evaluated every iteration and is used to compare the counter variable against a limit value. expression2 is executed at the end of each iteration and is used to increment the counter variable. Lets look at an example:

for ( $a = 0; $a < 3; $a++ ) {
  print ("<p>Hello World!</p>");
}

This is the output:

Hello World!
Hello World!
Hello World!

In the example above, you can probably tell how many times the For loop will iterate simply by looking at the code. We used $a as our control variable and initialized it to the value 0. Through each iteration, the value of $a is incremented by one ($a++) and tested by the condition statement ($a < 3). Ather three iterations the condition ($a < 3) becomes FALSE, since our control variable $a now equals 3 and the loop is exited.

The Do While Loop

Do While loops differ slightly from While loops because the statements in the code block are executed at least once regardless if the initial loop condition is false. The condition, in Do While loops is tested at the end instead of at the beginning of the code block.

do {
   ... // do this at least once
}
while ( condition );

Lets look at an example were we know the condition is false:

$a = 25;

do {
// this is executed once even though the condition evaluates to FALSE
  print ('$a = '.$a);
}
while ($a > 100);
$a = 25

Break and Continue

The Break statement is used to "break" or end execution of a loop. When the PHP interpreter encounters a Break statement within a loop it stops and exits the loop code block and executes the next instructions after the loop.

/* when $num == 10 PHP will execute this and then exit the loop even
though the loop condition $num < 20 is still TRUE */

for ($num = 2; $num < 20; $num++) {
  if ($num == 10) {
    echo '<br>';
    echo '$num'." = $num, I will exit now.";
    break;
  }
  else {
    echo $num;
  }
}
23456789
$num = 10, I will exit now.

The Continue statement is used within loops to jump to the next loop iteration.

  • Share/Bookmark

You can leave a response, or trackback from your own site.

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>