[main] [misc] [graphics] [page design] [site design] [xhtml] [css] [xml] [xsl] [schema] [javascript] [php] [mysql]

HVCC Home
Blackboard HVCC
Blackboard Manual
Faculty Association

php main
1. what is php
2. http basics
3. php basics
4. php expressions
5. php client side
6. php flow control
a. php conditionals
b. php adv conditions
* c. php iteration
d. php functions
e. php adv functions
f. php modularity
7. php manual


print version

Note that all external links will open up in a separate window.

This is a stripped down version of these pages for older browsers. These pages are really meant to be viewed in a standards compliant browser.

Directions for surfing with audio.

Iteration

These tutorials are about PHP and its use for server-side Web programming.

Iteration

Some statements in PHP are known as iterative statements. These statements have control structures that delimit them and which determine how many times (zero or more) the delimited code is executed, based on some condition.

We will look at three structures here

  • the while statement and its variants
  • the do ... while statement
  • the for statement

We will also look at some more advanced ways of working with iteration by being able to more freely move between nested iterative statements.

The while Statement

The while statement is the most basic of iterative control structures. It repeatedly runs a block of code until some condition is no longer true. If the condition is not true to begin with, then the code never runs. It takes the form of:

while (expression) {
  statements;
  }

For example, if we wanted to add together the first ten values from an array:

$x = 0;
while ($x < 10) {
  $a = $a + $b[$x];
  $x++;
  }

In the above code, we initialize a variable to zero (0) before beginning the loop. The while statement then evaluates the conditional expression. This expression must be inside parentheses. In this case , zero is less than 10, so the statement executes.

In the body of a while statement there must be some code that changes the value of the condition. Otherwise the loop will never terminate.

The last line in the statement block increments the variable we are testing in our conditional expression. In the body of a while statement there must be some code that changes the value of the condition. Otherwise the loop will never terminate. In the following code, the conditional expression will never become false, so the code will run forever (or until it crashes).

//  bad code -- an infinite loop
$x = 0;
$z = 0;
while ($x < 10) {
  $a = $a + $b[$z];
  $z++;
  }

infinite loop: an iterative code element that has no valid termination condition, meaning it will never stop looping

This state of endless execution is known as an infinite loop. Anyone with any programming experience is all too familiar with them. Their causes are many, and they are far too easy to create.

Like the if and switch statements from our previous lecture, while has an alternative label based syntax.

while (expression):
  statements;
endwhile;

The do ... while Statement

A while statement will never execute if its conditional expression never evaluates to true. What happens if you want the code to always run at least once, regardless of the value of its conditional expression?

The answer is use a do ... while statement.

A do ... while statement is like a while statement in reverse. First it runs the block of code, then it evaluates the conditional expression. If the conditional expression is true, then it loops back to the beginning of the statement and starts again.

It takes the form of:

do {
  statements;
  }
while (expression);

Note that since the curly brackets do not end the entire statement, we need a semi-colon at the end.

An example:

$x = 0;
do {
  $a =$ a + $b[$x];
  $x++;
  }
while ($x < 10);

This code will have the same effect as the equivalent while loop above. One that would work differently migh be as follows:

// will never run
// since the initial state of $x
// is $x != 10
$x = 0;
while ($x == 10) {
  $a = $a + $b[$x];
  $x++;
  }

// will run once
// even though the initial state of $x
// is $x != 10
$x = 0;
do {
  $a = $a + $b[$x];
  $x++;
  }
while ($x == 10);

A more practical use for this loop might be to check whether something has a value. For instance, you could walk an array as long as you keep finding values.

$x = 0;
do {
  if ($aName[$x]) {
    $bName[$x] = someProc($aName[$x]);
    }
  $x++;
  }
while (isset($aName[$x]));

In the preceeding example, we take advantage of the fact that non-existent value return false. This example assumes all the array elements are contiguous, since it will stop executing with the first empty array element it finds.

The do ... while has no alternative syntax, partly since anything you can do with a do ... while statement you can also do with a while statement. The do ... while is just easier to read in certain circumstances. It is also partly because the while , in occuring at the end, would be indistinguishable from a nested while loop if the curly brackets were omitted.

The for Statement

The for statement allows for incremental processing based on some incremental variable.

Unlike the while statement, the variable is incremented within the conditional expression itself. This means that you do not have to have code in the body of the statement to set the termination condition. This does not mean you that you cannot set the termination condition in the body, merely that you don't have to.

Once again, the statement keeps executing as long as the conditional statement is true.

It takes the form of:

for (init; condition; increment) {
  statements;
  }

The three values that go inside the for statement conditional expression are:

init
The initial state of the variable to be tested. Normally done as an assignment, although the assigned value can be from any source, literal or variable.
condition
The condition to be tested for. The statement keeps processing as long as it remains true.
increment
The increment by which the variable being tested changes.

For example:

for ($x = 0; $x < 10; $x++;) {
  $a = $a + $b[$x];
  $x++;
  }

For those who want to do things the hard way, you can also specify multiple conditions by putting them in a comma separated list within the semi-colon separated list.

for ($x=0,$y=0; $x<10,$y<20; $x++,incrF($y);) {
  $a = $a + $b[$x];
  $x++;
  }

This iterative structure also has an alternative syntax.

for (init; condition; increment):
  statements;
endfor;

for and while are not one-hundred percent interchangeable, so think about which one you want to use before coding.

The for statement assumes some sort of incrementation, such as counting through a set of something. It is designed for stepping through things.

flag: a variable, usually boolean, for reporting the current state of something in a program

Although any basic discussion of iteration tends to use incremental examples for both while and for statements, the while statement is better suited for testing some flag or condition. A flag, in programming terms, is a variable, usually boolean, that refers to the current state of something the in the program. Our example above of using a while statement to walk an array is an example where we are testing the contents of the elements of an array, not our position in it.

Termination Statements

Sometimes you want to break out of a control statement early, perhaps because of an error or some other condition that the conditional expression itself is not testing for. We have seen an example of this already with the break statement used in a switch statement coding block.

Here we will look at various ways to prematurely terminate loops and conditionals by setting multiple exit points.

The break Statement

break breaks you out of the conditional statement and moves on to the first statement outside of the conditional statement. When using break to get out of a condition, be aware that it ignores if statements. This is so you can use an if statement to test whether you need to terminate the current conditional.

For instance, we could use it to modify a previous do ... while statement. In the following example, the code will now terminate if the value to be processed is not an integer.

$x = 0;
$rVal = "";
do {
  if (isset($aName[$x])) {
    if (is_int($aName[$x])) {
      $rVal = "Bad Value";
      break;
      }
    $bName[$x] = someProc($aName[$x]);
    }
  $x++;
  }
while (isset($aName[$x]));

The continue Statement

If you are using an iterative statement and don't want to terminate it, just skip the current instance or iteration, you can use the continue statement. Continue says that the current iteration is done and the next one should be started. This is useful if the statement block has multiple possible exit points.

$x = 0;
$y = 0;
$rVal[0] = "";
do {
  if (isset($aName[$x])) {
    if (is_int($aName[$x])) {
      $rVal[$y] = "Bad Value at $aName[$x]";
      $x++;
      $y++;
      continue;
      }
    $bName[$x] = someProc($aName[$x]);
    }
  $x++;
  }

The following code is missing a single line compared to the one before it and is in error that will probably generate an infinite loop. This is because if it hits continue, it doesn't increment the conditional variable before beginning the next iteration, so it will just keep processing the same error over and over again.

// bad code - potential infinite loop
$x = 0;
$y = 0;
$rVal[0] = "";
do {
  if (isset($aName[$x])) {
    if (is_int($aName[$x])) {
      $rVal[$y] = "Bad Value at $aName[$x]";
      $y++;
      continue;
      }
    $bName[$x] = someProc($aName[$x]);
    }
  $x++;
  }

Stepping Out Multiple Levels

PHP also gives you the option to step out of multiple levels when working with nested conditional iterative statements. Once again, the if statement is not included in the since it is used to test whether to make such a step.

Both the break and the continue statements can be followed by a number specifying how many levels of nesting to step out. Best way to explain this to is create a little programmatic map:

statements;

// continue 4 jumps to here
while (loop 1 condition) {
  statements;

    // continue 3 jumps to here
    while (loop 2 condition) {
      statements;

      // continue 2 jumps to here
      while (loop3 condition) {
        statements;

        // continue or continue 1 jumps to here
        while (loop 4 condition) {
          statements;
          if (some condition) {
            break [or] continue #;
            }
          statements;
          }

        // break or break 1 jumps to here
       statements;
       }

     // break 2 jumps to here
     statements;
    }

  // break 3 jumps to here
  statements;
  }

// break 4 jumps to here
statements;

[top]