ÄúµÄλÖãºÑ°ÃÎÍøÊ×Ò³£¾±à³ÌÀÖÔ°£¾PHP ±à³Ì£¾PHP 5 Power programming
Team LiB
Previous Section Next Section

2.7. Control Structures

PHP supports a variety of the most common control structures available in other programming languages. They can be basically divided into two groups: conditional control structures and loop control structures. The conditional control structures affect the flow of the program and execute or skip certain code according to certain criteria, whereas loop control structures execute certain code an arbitrary number of times according to specified criteria.

2.7.1. Conditional Control Structures

Conditional control structures are crucial in allowing your program to take different execution paths based on decisions it makes at runtime. PHP supports both the if and switch conditional control structures.

2.7.1.1 if Statements

Statement

Statement List

if (expr)
       Statement
elseif (expr)
       Statement
elseif (expr)
       Statement
...
else
       Statement

if (expr):
       statement list
elseif (expr):
       statement list
elseif (expr):
       statement list
...
else:
       statement list
endif;


if statements are the most common conditional constructs, and they exist in most programming languages. The expression in the if statement is referred to as the truth expression. If the truth expression evaluates to TRue, the statement or statement list following it are executed; otherwise, they're not.

You can add an else branch to an if statement to execute code only if all the truth expressions in the if statement evaluated to false:

if ($var >= 50) {
       print '$var is in range';
} else {
       print '$var is invalid';
}

Notice the braces that delimit the statements following if and else, which make these statements a statement block. In this particular case, you can omit the braces because both blocks contain only one statement in them. It is good practice to write these braces even if they're not syntactically required. Doing so improves readability, and it's easier to add more statements to the if block later (for example, during debugging).

The elseif construct can be used to conduct a series of conditional checks and only execute the code following the first condition that is met.

For example:

if ($num < 0) {
       print '$num is negative';

} elseif ($num == 0) {
       print '$num is zero';
} elseif ($num > 0) {
       print '$num is positive';
}

The last elseif could be substituted with an else because, if $num is not negative and not zero, it must be positive.

Note

It's common practice by PHP developers to use C-style else if notation instead of elseif.


Both styles of the if construct behave in the same way. While the statement style is probably more readable and convenient for use inside PHP code blocks, the statement list style extends readability when used to conditionally display HTML blocks. Here's an alternative way to implement the previous example using HTML blocks instead of print:

<?php if ($num < 0): ?>
<h1>$num is negative</h1>
<?php elseif($num == 0): ?>
<h1>$num is zero</h1>
<?php elseif($num > 0): ?>
<h1>$num is positive</h1>
<?php endif; ?>

As you can see, HTML blocks can be used just like any other statement. Here, only one of the HTML blocks are displayed, depending on the value of $num.

Note

No variable substitution is performed in the HTML blocks. They are always printed as is.


2.7.1.2 switch Statements

Statement

Statement List

switch (expr){
     case expr:
          statement list
     case expr:
          statement list
     ...
     default:
          statement list
}

switch (expr):
     Case expr:
          statement list
     case expr:
          statement list
     ...
     default:
          statement list
endswitch;


You can use the switch construct to elegantly replace certain lengthy if/elseif constructs. It is given an expression and compares it to all possible case expressions listed in its body. When there's a successful match, the following code is executed, ignoring any further case lines (execution does not stop when the next case is reached). The match is done internally using the regular equality operator (==), not the identical operator (===). You can use the break statement to end execution and skip to the code following the switch construct. Usually, break statements appear at the end of a case statement list, although it is not mandatory. If no case expression is met and the switch construct contains default, the default statement list is executed. Note that the default case must appear last in the list of cases or not appear at all:

switch ($answer) {
    case 'y':
    case 'Y':
        print "The answer was yes\n";
        break;
    case 'n':
    case 'N':
        print "The answer was no\n";
        break;
    default:
        print "Error: $answer is not a valid answer\n";
        break;
}

2.7.2. Loop Control Structures

Loop control structures are used for repeating certain tasks in your program, such as iterating over a database query result set.

2.7.2.1 while loops

Statement

Statement List

while (expr)
statement

while expr):
statement list
endwhile;


while loops are the simplest kind of loops. In the beginning of each iteration, the while's truth expression is evaluated. If it evaluates to true, the loop keeps on running and the statements inside it are executed. If it evaluates to false, the loop ends and the statement(s) inside the loop is skipped. For example, here's one possible implementation of factorial, using a while loop (assuming $n contains the number for which we want to calculate the factorial):

$result = 1;
while ($n > 0) {
    $result *= $n--;
}
print "The result is $result";

2.7.2.2 Loop Control: break and continue
break
break expr
continue
continue expr

Sometimes, you want to terminate the execution of a loop in the middle of an iteration. For this purpose, PHP provides the break statement. If break appears alone, as in

break;

the innermost loop is stopped. break accepts an optional argument of the amount of nesting levels to break out of,

break n

which will break from the n innermost loops (break 1; is identical to break;). n can be any valid expression.

In other cases, you may want to stop the execution of a specific loop iteration and begin executing the next one. Complimentary to break, continue provides this functionality. continue alone stops the execution of the innermost loop iteration and continues executing the next iteration of that loop. continue n can be used to stop execution of the n innermost loop iterations. PHP goes on executing the next iteration of the outermost loop.

As the switch statement also supports break, it is counted as a loop when you want to break out of a series of loops with break n.

2.7.2.3 do...while Loops
do
    statement
while (expr);

The do...while loop is similar to the previous while loop, except that the truth expression is checked at the end of each iteration instead of at the beginning. This means that the loop always runs at least once.

do...while loops are often used as an elegant solution for easily breaking out of a code block if a certain condition is met. Consider the following example:

do {
    statement list
    if ($error) {
        break;
    }
    statement list
} while (false);

Because do...while loops always iterate at least one time, the statements inside the loop are executed once, and only once. The truth expression is always false. However, inside the loop body, you can use the break statement to stop the execution of the statements at any point, which is convenient. Of course, do...while loops are also often used for regular iterating purposes.

2.7.2.4 for Loops

Statement

Statement List

for (expr, expr, ᭻ expr, expr, ᭻ expr, expr, ᭩
statement

for (expr, expr, ᭻ expr, expr, ᭻ expr, expr, ᭩:
statement list
endfor;


PHP provides C-style for loops. The for loop accepts three arguments:

for (start_expressions; truth_expressions; increment_expressions)

Most commonly, for loops are used with only one expression for each of the start, truth, and increment expressions, which would make the previous syntax table look slightly more familiar.

Statement

Statement List

for (expr; expr; expr)
statement

for (expr; expr; expr):
statement list
endfor;


The start expression is evaluated only once when the loop is reached. Usually it is used to initialize the loop control variable. The truth expression is evaluated in the beginning of every loop iteration. If true, the statements inside the loop will be executed; if false, the loop ends. The increment expression is evaluated at the end of every iteration before the truth expression is evaluated. Usually, it is used to increment the loop control variable, but it can be used for any other purpose as well. Both break and continue behave the same way as they do with while loops. continue causes evaluation of the increment expression before it re-evaluates the truth expression.

Here's an example:

for ($i = 0; $i < 10; $i++) {
    print "The square of $i is " . $i*$i . "\n";
}

The result of running this code is

The square of 0 is 0
The square of 1 is 1
...
The square of 9 is 81

Like in C, it is possible to supply more than one expression for each of the three arguments by using commas to delimit them. The value of each argument is the value of the rightmost expression.

Alternatively, it is also possible not to supply an expression with one or more of the arguments. The value of such an empty argument will be true. For example, the following is an infinite loop:

for (;;) {
       print "I'm infinite\n";
}

Tip

PHP doesn't know how to optimize many kinds of loop invariants. For example, in the following for loop, count($array) will not be optimized to run only once.

for ($i = 0; $i <= count($array); $i++) {
}

It should be rewritten as
$count = count($array);
for ($i = 0; $i <= $count; $i++) {
}

This ensures that you get the best performance during the execution of the loop.


2.7.3. Code Inclusion Control Structures

Code inclusion control structures are crucial for organizing a program's source code. Not only will they allow you to structure your program into building blocks, but you will probably find that some of these building blocks can later be reused in other programs.

2.7.3.1 include Statement and Friends

As in other languages, PHP allows for splitting source code into multiple files using the include statement. Splitting your code into many files is usually helpful for code reuse (being able to include the same source code from various scripts) or just in helping keep the code more maintainable. When an include statement is executed, PHP reads the file, compiles it into intermediate code, and then executes the included code. Unlike C/C++, the include statement behaves somewhat like a function (although it isn't a function but a built-in language construct) and can return a value using the return statement. Also, the included file runs in the same variable scope as the including script (except for the execution of included functions which run with their their own variable scope).

The prototype of include is

include file_name;

Here are two examples for using include:

  • error_codes.php

    <?php
    
        $MY_OK = 0;
        $MY_ERROR = 1;
    ?>
    

  • test.php

    <?php
    
        include "error_codes.php";
    
        print ('The value of $MY_OK is ' . "$MY_OK\n");
    ?>
    

    This prints as
    The value of $MY_OK is 0
    

You can use both relative and absolute paths as the file name. Many developers like using absolute path names and create it by concatenating the server's document root and the relative path name. This allows them great flexibility when moving their PHP application among different servers and PHP installations. For example:

include $_SERVER["DOCUMENT_ROOT"] . "/myscript.php";

In addition, if the INI directive, allow_url_fopen, is enabled in your PHP configuration (the default), you can also include URLs. This method is not recommended for performance reasons because PHP must first download the source code to be included before it runs it. So, use this option only when it's really necessary. Here's an example:

include "http://www.example.org/example.php";

The included URL must return a valid PHP script and not a web page which is HTML (possibly created by PHP). You can also use other protocols besides HTTP, such as FTP.

When the included file or URL doesn't exist, include emits a PHP warning but does not halt execution. If you want PHP to error out in such a case (usually, this is a fatal condition, so that's what you'd probably want), you can use the require statement, which is otherwise identical to include.

There are two additional variants of include/require, which are probably the most useful. include_once/require_once which behave exactly like their include/require counterparts, except that they "remember" what files have been included, and if you try and include_once/require_once the same file again, it is just ignored. This behavior is similar to the C workaround for not including the same header files more than once. For the C developers among you, here's pretty much the require_once equivalent in C:

my_header.h:

#ifndef MY_HEADER_H
#define MY_HEADER_H 1

... /* The file's code */

#endif

2.7.3.2 eval()

eval() is similar to include, but instead of compiling and executing code that comes from a file, it accepts the code as a string. This can be useful for running dynamically created code or retrieving code from an external data source manually (for example, a database) and then executing it. As the use of eval() is much less efficient than writing the code as part of your PHP code, we encourage you not to use it unless you can't do without:

$str = '$var = 5;';
eval($str);
print $var;

This prints as
5

Tip

Variables that are based on user input should never be directly passed to eval() because this might allow the user to execute arbitrary code.


    Team LiB
    Previous Section Next Section