Приглашаем посетить
Чулков (chulkov.lit-info.ru)

Program Flow Control Structures

Table of Contents
Previous Next

Program Flow Control Structures

Flow control structures are used to dictate which statement should execute when, and under what circumstances. As with all other programming languages, PHP's flow control structures broadly fall into two categories: conditional statements and loops.

Conditional Statements

Conditional statements such as if and switch allow different blocks of code to be executed depending on the circumstances at the time of execution.

if

PHP's if statement has several possible forms. The simplest syntax is:

            if (condition) statement;

condition can be any expression that evaluates to a Boolean (true or false) value. statement only executes if condition evaluates to true. Usually, statements are listed in a block inside curly braces. This is easier to read and allows multiple statements to execute based on the results of a single condition:

    if ($bIsMorning) {
        $sGreeting = "Good morning";
        echo($sGreeting);
    }

We often need to specify what should happen if the same condition evaluates to false. One (not very good) possibility would be to use a second if statement with a NOT (!) operator:

    if ($bIsMorning) {
        $sGreeting = "Good morning";
    }
    if (!$bIsMorning) {
        $sGreeting = "Hello";
    }
    echo($sGreeting);

Almost all programming languages, including PHP, offer a much better alternative: else. The following example is equivalent to the previous example:

    if ($bIsMorning) {
        $sGreeting = "Good morning";
    } else {
        $sGreeting = "Hello";
    }
    echo($sGreeting);

elseif is used to test additional conditions. An if statement can take as many elseif statements as you like; however, each if statement may only have one else, since else specifies what should be done if no other conditions evaluated to true:

    if ($bIsMorning) {
        $sGreeting = "Good morning";
    } elseif ($bIsAfternoon) {
        $sGreeting = "Good afternoon";
    } elseif ($bIsEvening) {
        $sGreeting = "Good evening";
    } else {
        $sGreeting = "Hello";
    }
    echo($sGreeting);

The statements associated with an elseif or an else will be executed only if every condition tested before it evaluates to false. Therefore, in the example below, if $iHour's value is 10, only "Good morning" is printed, even though 10 is also less than 17. However, if $iHour's value is 14, only "Good afternoon" is printed:

    if ($iHour < 12) {
        $sGreeting = "Good morning";
    } elseif ($iHour < 17) {
        $sGreeting = "Good afternoon";
    } else {
        $sGreeting = "Good evening";
    }
    echo($sGreeting);

PHP offers an alternate if syntax that does not use curly braces. The alternate syntax is often used to allow different blocks of client-side code (XHTML, CSS, or JavaScript) to be used, depending on the value of the condition. In the following example, the first table will be included in the page only if $sSeason's value is summer. If the variable's value is winter, the second table will appear. Note that in this syntax an endif is necessary, since there is no } to indicate the end of the if block:

    <?php
    if ($sSeason == "summer"):
    ?>

    <table>
      <caption>Summer Data</caption>
      ...
      ...
    </table>

    <?php
    elseif ($sSeason == "winter"):
    ?>

    <table>
      <caption>Winter Data</caption>
      ...
      ...
    </table>

    <?php
    endif;
    ?>

Many simple if-else statements can be replaced with the ternary operator, especially those that are used to assign a value to a single variable. For example, the following code:

    if ($sSeason == "summer") {
        $fPrice = 35.95;
    } else {
        $fPrice = 30.95;
    }

can be replaced with:

    $fPrice = ($sSeason == "summer" ? 35.95 : 30.95);

For more information about the ternary operator, see Chapter 3.

switch

The switch statement is used to evaluate a single expression and produce multiple possible results depending on the expression's value:

          switch (expression) {
          case value1:
              statements;
              break;

          case value2:
              statements;
              break;

          default:
              statements;
          }

In the example below, switch evaluates $sLangCode and compares its value to the value of each case label. When it finds one that matches, it executes that case statement's code until it encounters a break statement. If no case label matches the value of $sLangCode, the default code executes:

    switch ($sLangCode) {
    case "fr":
        echo("French");
        break;

    case "es":
        echo("Spanish");
        break;

    case "en":
        echo("English");
        break;

    case "de":
        echo("German");
        break;

    case "ru":
        echo("Russian");
        break;

    default:
        echo("Language not recognized in system.");
    }

When a break statement is encountered, execution of the switch statement is halted and is resumed past the switch statement's close curly brace.

Once a case label is found that matches the value in question, no other case labels will be evaluated, so omitting the break statement at the end of a case causes execution to fall through to all subsequent cases, even though those values do not match. It is a common mistake for beginners to accidentally omit break and end up with the results of multiple cases. However, "fall through" isn't a bug; it's a feature. It allows the programmer to produce the same results for more than one case:

    switch ($sLangCode) {
    case "fr": // Fall through:

    case "es":
        echo("Romance language");
        break;

    case "en": // Fall through:

    case "de":
        echo("Germanic language");
        break;

    case "ru":
        echo("Slavic language");
        break;

    default:
        echo("Language not recognized in system.");
    }

It is good programming practice to include comments like those in the example above to make it clear that the omission of the break statement is intentional. In this example, "Romance language" will print whether the value is fr or es, so the effect is similar to that of using an OR (||) operator in an if statement.

In other instances, however, fall through is even more flexible than OR. In the following example, both statement1 and statement2 will execute if $sLangCode's value is fr, but only statement2 will execute if the value is es:

    switch ($sLangCode) {
    case "fr":
        statement1; // Fall through:

    case "es":
        statement2;
        break;
    }

In the examples above, we use literal values for our case labels. In PHP, unlike most other languages, case labels may themselves be variables. Not even JavaScript (which is pretty liberal as far as programming languages go) is that flexible. Arrays and objects are the only data types that are not legal as case labels in PHP.

Loops

Loops allow a block of code to execute a given number of times, or until a certain condition is met. They are often used for tasks like accessing records from a database query, reading lines from a file, or traversing the elements of an array. There are four types of loop in PHP: while, do while, for, and foreach. The first three are described below. foreach is described when we discuss arrays later in the chapter.

while

while is the simplest loop statement. It tests a condition and repeatedly executes a block of statements as long as that condition evaluates to true at the beginning of each iteration:

            while (condition) {
            statements
            }

Loops are often used with increment or decrement operators to control when to start and stop the loop. The variables used for this purpose (such as $i in the example below) are sometimes called loop control variables:

    echo ("<select name=\"num_players\">\n");
    $i = 0;

    while (++$i <= $iMaxPlayers) {
        echo("<option value=\"$i\">$i</option>\n");
    }

    echo("</select>\n");

In some loops, a Boolean variable serves as the loop control variable. For example, a loop that reads lines from a file might use a variable like $bEOF to continue as long as the end of the file has not been reached.

The break statement is used to halt a loop. When break is encountered, the current iteration of the loop stops and no further iterations occur:

    echo("<select name=\"num_players\">\n");
    $i = 0;

    while (++$i <= $iMaxPlayers) {
        if (! is_legal_val($i)) {
            break; // Stop adding options to the select element
        }
        echo("<option value=\"$i\">$i</option>\n");
    }

    echo("</select>\n");

In some situations we may wish to halt only the current iteration and skip ahead to the next iteration. For this we use the continue statement:


    echo("<select name=\"num_players\">\n");
    $i = 0;

    while (++$i <= $iMaxPlayers) {
        if (! is_legal_val($i)) {
            continue; // Skip ahead to next iteration.
            // Don't echo option for this value
        }
        echo("<option value=\"$i\">$i</option>\n");
    }

    echo("</select>\n");

do while

do while loops are similar to while loops, except that the condition is tested at the end of each iteration, rather than at the beginning. This means that the loop will always execute at least once. In the following example, zero will always be an option regardless of the value of $iMaxPlayers:

    echo("<select name=\"num_players\">\n");
    $i = 0;

    do {
        echo("<option value=\"$i\">$i</option>\n");
    } while (++$i <= $iMaxPlayers);

    echo("</select>\n");

for

The syntax of a for loop differs significantly from that of a while loop. The difference is primarily in the organization: a for loop places all of the expressions that control the flow of the loop on the first line:

            for (expression1; expression2; expression3) {
            statements
            }

expression1 is evaluated before the loop begins. It is typically used to initialize a loop control variable. expression2 is evaluated at the beginning of every iteration of the loop. It behaves as the conditional expression: if expression2 evaluates to true, the loop continues; if false, the loop halts. expression3 is evaluated at the end of each iteration, so it is ideal for incrementing or decrementing the loop control variable:

    echo("<select name=\"num_players\">\n");

    for ($i = 0; $i <= $iMaxPlayers; ++$i) {
        echo("<option value=\"$i\">$i</option>\n");
    }

    echo("</select>\n");

This example has the same effect as our example for do while. It creates a <select> element of options ranging from zero to $iMaxPlayers. The example demonstrates the most common (and intended) usage of a for construct: to initialize a control variable, test the variable against a value, and increment or decrement the value. However, for can also be used in other ways. Like in C and other languages, it is legal to leave one or more of the expressions blank (expression2 defaults to true if omitted):

    for ( ; ; ) {
        if (my_function() == "stop") break;
    }

This loop will continue to execute until my_function() returns the string "stop". While this is perfectly legal, it is not the clearest way to write the loop. This code could have been written more sensibly:

    while (my_function() != "stop");

Alternative Syntax for Loops

Like the if statement, the different loops also support an alternative syntax:

    <?php
    while (my_function() > 0):
    ?>

    <tr><td><input type="text" /></td></tr>

    <?php
    endwhile;
    ?>

    ...

    <?php
    for ($i = 10; $i > $iMinScore; --$i):
    ?>

    <li>Another XHTML list item</li>

    <?php
    endfor;
    ?>

Table of Contents
Previous Next