Team LiB
Previous Section Next Section

Control Structures

Logical Control Structures

Although all the variable manipulations that have been covered thus far are wonderful, they leave much to be desired in terms of a real programming language. For that, you need control structures. Control structures are a facility that allows you to control the behavior of your programs. Control structures enable you to specify the circumstances under which code will be executed, generally based on the current state of the script. Often, they can even be (roughly at least) translated from plain English. To illustrate this, consider what is called a conditional statement in programming:

"If John finishes 15 pages of his book, then he can sleep."

How can this logic be transformed into a computer program that can tell me when it's all right for me to go to sleep? To compare how many pages I've written to how many I need to complete, I'll need to use the if statement. The if statement is unlike anything covered thus far and takes the following general form:

if(conditions) {
    /* Code to execute if condition is true */
} [ else {
    /* Code to execute if condition is false */
} ]

conditions is any expression, evaluated as a Boolean value.

NOTE

When the general syntax of a function is described in this book, brackets around a portion of it (such as those around the else portion of this description) are used to indicate optional portions of the statement and can be left off in practical use if desired. Furthermore, cases may exist later in the book where these brackets are embedded within other brackets to indicate that they are optional portions of an already optional portion of a statement.


A single-line version of the if statement also exists in the following form:

if (conditions) /* Code if true */;

To better illustrate how the if statement is actually used, consider the examples shown in Listing 1.11:

Listing 1.11. Basic Use of the if Statement
<?php

    if (true) echo "This will always display!<BR>";

    if (false) {

        echo "This will never, ever be displayed.<BR>";

    } else {

        echo "This too will always display!<BR>";

    }
?>

Which generates the following output:

This will always display!
This too will always display!

The PHP if statement is the most fundamental control structure and is designed to execute what is called a block of code if, and only if, the condition statement provided to it is evaluated to a Boolean TRue (I will explain later what a "Boolean" is). How do you know if a statement is true? PHP provides a number of methods, described in Table 1.2; each will equal either the Boolean value TRue or false as shown:

Table 1.2. Comparison Operators

Operator Example

Action

$foo == $bar

TRue if $foo equals $bar

$foo === $bar

true if $foo equals $bar, and $foo and $bar are of the same type

$foo != $bar

TRue if $foo doesn't equal $bar

$foo !== $bar

true if $foo doesn't equal $bar or $foo and $bar are different types

$foo < $bar

true if $foo is less than $bar

$foo > $bar

true if $foo is more than $bar

$foo <= $bar

true if $foo is less than or equal to $bar

$foo >= $bar

TRue if $foo is more than or equal to $bar


NOTE

Although in general the condition part of an if statement should equal either the predefined Boolean value TRue or false, integer values greater than zero are also considered true, whereas zero itself is considered false. Regardless, it is strongly recommended that the actual Boolean values provided by PHP be used when you are working with conditional statements.


So how do these comparison operators work? Basically, like the mathematical operations described earlier:

<?php
    $answer = (14 < 15);      /* $answer == false */
    $answer = (14 <= 15);     /* $answer == true */
?>

Hopefully, you now should have an idea of how to write the short script example that will be able to describe when it's time for me to get some sleep (see the conditional statement at the start of this section if you skipped ahead). Listing 1.12 shows what I came up with:

Listing 1.12. Using Comparison Operators in if Statements
<?php

    $pgs_complete = 14;

    if ($pgs_complete < 15) {

        echo "Sorry! You can't sleep yet, John.<BR>";

    } else {

        echo "Congratulations, Get some sleep already!!<BR>";

    }
?>

This is all wonderful for situations where only one condition exists per code block, but what about situations in which two or more conditions must be met? One solution is to embed one or more if statements within an if statement, such as the following (see Listing 1.13):

Listing 1.13. Embedded Conditionals
<?php

    if($value > 0) {

        if($value <= 10) {

            echo 'The $value variable is between 1 and 10.';

        } else {

            if($value <= 20) {

                echo 'The $value variable is between 1 and 20.';

            } else {

                echo 'The $value variable is greater than 20';
            }

        }
    }

?>

TIP

Anything can be embedded within a code block, including another code block statement. There is no limit to how many layers "deep" code blocks can be, although it is good practice to limit the embedding of code blocks to keep the code easy to read.


Although this works, there is a better way. When multiple conditions are required, PHP can use logical operators to combine multiple conditions into a single Boolean value. For instance, consider the following conditional statement:

"If John finishes 15 pages, or there is nothing more to write, he can go to sleep."

For this particular statement, I could get some sleep if I finish 15 pages or if I finish writing. Although I could create this logic with two separate if statements, it is not the best solution. The proper way to deal with this is to create a single multiconditional if statement.

As you may recall from my initial introduction of the if statement, the conditional portion of the statement is an expression that is evaluated as a Boolean. Thus, to create a multiconditional if statement, all that is needed is a set of Boolean operators. These operators, called logical operators are shown in Table 1.3:

Table 1.3. Logic Operators in PHP

Operator

Action

$foo and $bar

TRue if $foo and $bar are TRue

$foo or $bar

true if $foo or $bar is true

$foo xor $bar

true if and only if $foo or $bar is true (only one or the other)

!$foo

true if $foo is not true

$foo && $bar

TRue if $foo and $bar are true

$foo || $bar

true if $foo or $bar is true


NOTE

Although it seems identical, the and/or operators are not the same as the && and || operators. The difference is the precedence in which they are processed. In PHP, and/or operators are processed before the && and || operators. Because of this, it is strongly recommended that parentheses be used to define the order of operations for any complex expression.

<?php
        $answer = ($a < $b) || ($c > $d) /* good */
        $answer = $a < $b || $c > $d     /* bad */
?>


With this knowledge in hand, let's take a look at the code that would represent the preceding multiconditional statement, as shown in Listing 1.14:

Listing 1.14. Multiconditional if Statements
<?php

    $finished = true;
    $pgs_complete = 14;

    if ( ($pgs_complete >= 15) || $finished)) {

        echo "Hey you're done, get some sleep!<BR>";

    } else {

        echo "You're not done yet -- no sleep tonight!<BR>";

    }
?>

Although this is great, there are still improvements that can be made regarding the else portion of the logic. Earlier, I presented a chunk of code that had an embedded if statement in the else portion of another conditional similar to that found in Listing 1.13.

NOTE

In situations in which you are using a conditional to determine the value of a variable, the following syntax can be used:

$variable = (conditional) ? /* true */ : /* false */;

$variable will be assigned the value in the first segment if the conditional is TRue or assigned the value in the second segment if the conditional is false.


In situations like this, the code involved can be somewhat simplified by using the PHP elseif statement. In use, the elseif statement replaces else in an if conditional, as follows:

if(conditional) {
    /* Code block to execute if conditional is true */
} elseif(conditional) {
    /* Code block to execute if the first conditional is 
       false, but second conditional is true */
} else {
    /* Code to execute if both conditionals are false */
}

Note that as many elseif statements as designed can be strung together to achieve the desired code flow. This statement should be used only when multiple complex conditionals are required in the design of the script. For simpler situations, let's take a look at a completely new control structurethe switch statement.

As with all but the most fundamental of control structures, the switch statement is a simplified way to perform tasks that can be done with the basic if statement. The purpose of the switch statement is to enable the developer to assign a block of code to each of a number of different "cases" (possible values) that a given variable, called a control variable, can be. The general form of the switch statement is as follows:

switch($variable) {
    [case <constant>:]
        /* code to execute if $variable equals 1 */
        [break;]
    [case <constant>:]
        /* code to execute if $variable equals 2 */
        [break;]
    ...additional cases
    [default:]
        /* code to execute if no case matches */
}

TIP

case constants are not limited to integer values as in other languages such as C. In PHP, any constant value including strings and floating point numbers may be used.


In use, the switch statement is provided a single variable whose value is compared against those provided in each individual case statement. In fact, the switch statement is indeed similar to a series of if statements as illustrated in Listing 1.15:

Listing 1.15. Using if Statements to Mimic a select Statement
<?php

    /* Using the if statement method */
    if($i == 0) echo 'First case';
    if($i == 1) echo 'Second case';

    /* The same code as above, using a switch statement */
    switch($i) {

        case 0:]

            echo 'First case';
            break;

        case 1:

            echo 'Second case';
            break;

    }
?>

Note that when you use the switch statement, the break statement at the end of each code block is optional. If a break statement is not used, PHP will continue through the switch statement, executing each case until a break is encountered or the end of the switch statement is reached, as shown in Listing 1.16.

Listing 1.16. Using the switch Statement
<?php
    switch($i) {

        case 1:

            echo 'First case<BR>';

        case 2:

            echo 'Second case<BR>';
            break;

        default:
            echo 'Default case';
    }
?>

If the value of the $i variable is 1, both the first and second cases will be executed because a break statement exists at the end of case 2. The result is the following for a value of $i = 1:

First case
Second case

Repetition Control Structures

Now that you have some idea of how to do basic comparisons within your scripts, let's take a look at another fundamental programming conceptthe repeated iteration of a block of code. The capability to repeat the same task over and over is paramount to why computers are so powerful; you can use various methods to accomplish this repeated iteration (called looping) in PHP scripts. Let's start with the simplest one, called a while loop.

Although functionally different, the PHP while statement is similar to the if statement, including its support for multiple conditions using logical operators. The general syntax of the while statement is as follows:

while (condition) {
      /* Code to execute repetitively until the provided     
         condition is false*/
}

Or in its single-line form:

while (condition) /* code to execute */;

With this statement, tasks that were impossible before, such as making a script that can count, are now quite simple. If you want to write a script that displays every number divisible by 3 between 1 and 300 and that prints out every odd number, something like the code in Listing 1.17 would do the trick:

Listing 1.17. Using the while Statement
<?php

    $count = 1;

    while ($count <= 300) {

        if ( ($count % 3) == 0) {

            echo "$count is divisible by 3!<BR>";

        }

        $count++;
    }

?>

When you look at the preceding script, a number of things that you haven't been exposed to yet might throw you off. Note that within the while statement, you are incrementing the $count variable. Without this line of code, the condition on which the while statement terminates (when $count reaches 300) would never be met. The situation I am describing is called an infinite loop and is a common mistake among beginner (and sometimes even expert) programmers. Although the while statement is the most common place where infinite loops can occur, almost all repetition statements in PHP can create an infinite loop situation. Care must be taken in any PHP loop that the condition for termination of the loop will eventually be met or avoid an infinite loop.

Like most control structures in PHP, multiple flavors of the while loop exist, each with slightly different syntax and behavior. One of those is the do/while loop. The general syntax of the do/while loop is as follows:

do {
    /* Code to execute */
} while(condition);

Unlike the while statement, the do/while statement will always execute the code within its code block at least once. Whether the code is executed multiple times is determined by the condition within the while part of the statement. If this condition evaluates to TRue, the code is executed again until the condition is false. Although not often used, the do/while statement can be useful under certain circumstances.

Although the do/while or while loops can conceptually handle every type of situation in which a loop is required, many specialized loop statements exist in PHP. One of the most common types of specialized loops is called the for loop and is generally used when the counting of a variable is required. The syntax for the for loop is as follows:

for (initialization;condition;post-execution) {
    /* code to execute while condition is true */
}

As you can see, the parameters for the for statement are slightly more complicated than those for its counterpart, the while statement. Specifically, the for statement parameter is divided into three independent segments. The first segment, called the initialization segment, is executed as soon as the for statement is encountered within a script and is used to initialize any variables used within the loop. The second segment, called the condition segment, determines under what conditions the for statement will stop executing the code within its code block. The final segment, called the post-execution segment, is executed immediately following the end of the for statement's code block.

So how does this thing work? It depends on how hard and fast you want to hold to convention. Technically, any valid PHP statements can be placed in each of the three separate segments, and everything will work just fine. However, as I've already mentioned, the for statement was designed for situations in which counting is involved. Let's look at the earlier example using the while loop where we wanted to print out every number between 1 and 300 that was divisible by 3. To implement the same code using the for loop, it would look something like Listing 1.18:

Listing 1.18. Using the for statement
<?php

    for ($count = 1; $count <= 300; $count++) {

        if ( ($count % 3) == 0) {

             echo "$count is divisible by 3!<BR>";

        }

    }

?>

As you can see, the first segment of the for loop (the initialization segment) is used to initialize the $count variable to 1. Then the code block is executed and the third segment of the loop (the post-execution segment) increments the $count variable by one until the middle segment (the condition segment) is no longer true. When executed, this code produces the exact results it did previously when using the while statement.

Embedding Control Structures

Now that you have been exposed to the majority of PHP control structures, it's time to discuss how these control structures can be used more effectively to produce HTML tags (or any other output). As you are already aware, PHP is an embedded language that enables you to code both your HTML tags and the supporting script in the same document. However, PHP takes this concept a step further by allowing you to "turn off" the PHP parser during a control structure and embed non-PHP output without losing the logic provided by the control structure.

Let's look at an example where you would like to display an image in your HTML document only when the variable $display is set to TRue. For a beginner, the most common solution is as follows:

<?php

    if($display) {
        echo "<IMG SRC=\"/gfx/mypicture.jpg\">";
    }

?>

Although completely functional, it's obvious that this solution is somewhat messy. To address this problem, there is an alternate syntax for your favorite control structures in PHP that allows you to exit the PHP parser and pass output directly through PHP. For the if statement, this syntax is as follows:

<?php ... if (conditional): ?>
Text that should be output, but not parsed
<?php endif; ?>

In the case of the previous example, this syntax could be applied as follows to produce the same behavior as shown earlier:

<?php if($display): ?>
<IMG SRC="/gfx/mypicture.jpg">
<?php endif; ?>

This alternative syntax is available for every PHP control structure. Instead of a brace ({), a colon (:) is used to start the control structure, and each control structure is terminated by the appropriate end statement (endif, endwhile, endfor, and so on). Generally, this alternative syntax is used when you want to display non-PHP parsed code, but it can be used anywhere within PHP scripts. Furthermore, this syntax is not necessary to prevent PHP from parsing a particular segment of the document. The following is also completely acceptable, although prone to be more confusing with complexity:

<?php if($display) { ?>
<IMG SRC="/gfx/mypicture.jpg">
<?php } ?>

Note that turning off the PHP parser is not limited to control structures. At any point within a script, the parser can be turned off by using an acceptable PHP close tag and turned back on with an acceptable PHP open tag (see the description of acceptable tags earlier in this chapter).

    Team LiB
    Previous Section Next Section