JavaScript Editor Javascript source editor     Web programming 



Team LiB
Previous Section Next Section

Switching Flow

It is common for scripts to evaluate conditions and change their behavior accordingly. These decisions are what make your PHP pages dynamic; that is, able to change output according to circumstances. Like most programming languages, PHP allows you to do this with an if statement.

The if Statement

The if statement is a way of controlling the execution of a statement that follows it (that is, a single statement or a block of code inside braces). The if statement evaluates an expression found between parenthesesif this expression results in a TRue value, the statement is executed. Otherwise, the statement is skipped entirely. This functionality enables scripts to make decisions based on any number of factors:

if (expression) {
   // code to execute if the expression evaluates to true
}

Listing 6.1 executes a block of code only if a variable contains the string "happy".

Listing 6.1. An if Statement
1: <?php
2: $mood = "happy";
3: if ($mood == "happy") {
4:     echo "Hooray, I'm in a good mood!";
5: }
6: ?>

In line 2, the value of "happy" is assigned to the variable $mood. In line 3, the comparison operator == compares the value of the variable $mood with the string "happy". If they match, the expression evaluates to TRue, and the subsequent code is executed until the closing bracket is found (in this case, in line 5).

Put these lines into a text file called testif.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

Hooray, I'm in a good mood!

If you change the assigned value of $mood to "sad" or any other string besides "happy", then run the script again, the expression in the if statement will evaluate to false, and the code block will be skipped. The script remains silent, which leads us to the else clause.

Using the else Clause with the if Statement

When working with an if statement, you might want to define an alternative block of code that should be executed if the expression you are testing evaluates to false. You can do this by adding else to the if statement followed by a further block of code:

if (expression) {
   // code to execute if the expression evaluates to true
} else {
   // code to execute in all other cases
}

Listing 6.2 amends the example in Listing 6.1 so that a default block of code is executed if the value of $mood is not equivalent to "happy".

Listing 6.2. An if Statement That Uses else
1: <?php
2: $mood = "sad";
3: if ($mood == "happy") {
4:     echo "Hooray, I'm in a good mood!";
5: } else {
6:     echo "I'm in a $mood mood.";
7: }
8: ?>

Put these lines into a text file called testifelse.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

I'm in a sad mood.

Notice in line 2 that the value of $mood is the string "sad", which obviously is not equal to "happy", so the expression in the if statement in line 3 evaluates to false. This results in the first block of code (line 4) being skipped. However, the block of code after else is executed, and the alternate message is printed: I'm in a sad mood.. The string "sad" is the value assigned to the variable $mood.

Using an else clause in conjunction with an if statement allows scripts to make decisions regarding code execution. However, your options are limited to an either-or branch: either the code block following the if statement, or the code block following the else statement. You'll now learn about additional options for the evaluation of multiple expressions, one after another.

Using the else if Clause with the if Statement

You can use an if...else if...else clause to test multiple expressions (the if...else portion) before offering a default block of code (the else if portion):

if (expression) {
   // code to execute if the expression evaluates to true
} else if (another expression) {
   // code to execute if the previous expression failed
   // and this one evaluates to true
} else {
   // code to execute in all other cases
}

If the initial if expression does not evaluate to true, the first block of code will be ignored. The else if clause presents another expression for evaluation; if it evaluates as true, its corresponding block of code is executed. Otherwise, the block of code associated with the else clause is executed. You can include as many else if clauses as you want, and if you don't need a default action, you can omit the else clause.

By the Way

The else if clause can also be written as a single word (elseif). The syntax you employ is a matter of taste.


Listing 6.3 adds an else if clause to the previous example.

Listing 6.3. An if Statement That Uses else and else if
1: <?php
2: $mood = "sad";
3: if ($mood == "happy") {
4:     echo "Hooray, I'm in a good mood!";
5: } else if ($mood == "sad") {
6:     echo "Awww. Don't be down!";
7: } else {
8:     echo "Neither happy nor sad but $mood.";
9: }
10:?>

Once again, the $mood variable has a value of "sad", as shown in line 2. This value not equal to "happy", so the code in line 4 is ignored. The else if clause in line 5 tests for equivalence between the value of $mood and the value "sad", which evaluates to TRue. This code in line 6 is therefore executed. In lines 7 through 9, a default behavior is provided, which would be invoked if the previous test conditions were all false. In this case, we simply print a message including the actual value of the $mood variable.

Put these lines into a text file called testifelseif.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

Awww. Don't be down!

Change the value of $mood to "iffy" and run the script, and it will produce the following:

Neither happy nor sad but iffy.

The switch Statement

The switch statement is an alternative way of changing flow, based on the evaluation of an expression. Using the if statement in conjunction with else if, you can evaluate multiple expressions, as you've just seen. However, a switch statement evaluates only one expression in a list of expressions, selecting the correct one based on a specific bit of matching code. Whereas the result of an expression evaluated as part of an if statement is interpreted as either TRue or false, the expression portion of a switch statement is subsequently tested against against any number of values, in hopes of finding a match:

switch (expression) {
       case result1:
            // execute this if expression results in result1
            break;
       case result2:
            // execute this if expression results in result2
            break;
       default:
            // execute this if no break statement
            // has been encountered hitherto
}

The expression used in a switch statement is often just a variable, such as $mood. Within the switch statement, you find a number of case statements. Each of these cases tests a value against the value of the switch expression. If the case value is equivalent to the expression value, the code within the case statement is executed. The break statement ends the execution of the switch statement altogether.

If the break statement is left out, the next case statement is executed, regardless if a previous match has been found. If the optional default statement is reached, without a previous matching value having been found, then its code is executed.

Watch Out!

It is important to include a break statement at the end of any code that will be executed as part of a case statement. Without a break statement, the program flow will continue to the next case statement and ultimately to the default statement. In most cases, this will result in unexpected behavior, likely incorrect!


Listing 6.4 re-creates the functionality of the if statement example, using the switch statement.

Listing 6.4. A switch Statement
1: <?php
2: $mood = "sad";
3: switch ($mood) {
4:     case "happy":
5:        echo "Hooray, I'm in a good mood!";
6:        break;
7:     case "sad":
8:        echo "Awww. Don't be down!";
9:        break;
10:     default:
11:         echo "Neither happy nor sad but $mood.";
12:         break;
13: }
14: ?>

Once again, in line 2 the $mood variable is initialized with a value of "sad". The switch statement in line 3 uses this variable as its expression. The first case statement in line 4 tests for equivalence between "happy" and the value of $mood. There is no match, so script execution moves on to the second case statement in line 7. The string "sad" is equivalent to the value of $mood, so this block of code is executed. The break statement in line 9 ends the process. Lines 10 through 12 provide the default action, should neither of the previous cases evaluate as true.

Put these lines into a text file called testswitch.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

Awww. Don't be down!

Change the value of $mood to "happy" and run the script, and it will produce the following:

Hooray, I'm in a good mood!

To emphasize the caution regarding the importance of the break statement, try running this script without the second break statement. Your output will be

Awww. Don't be down!Neither happy nor sad but sad.

This is definitely not the desired output, so be sure to include break statements where appropriate!

Using the ? Operator

The ? or ternary operator is similar to the if statement, except that it returns a value derived from one of two expressions separated by a colon. This construct will provide you with three parts of the whole, hence the name ternary. The expression used to generate the returned value depends on the result of a test expression:

(expression) ? returned_if_expression_is_true : returned_if_expression_is_false;

If the test expression evaluates to TRue, the result of the second expression is returned; otherwise, the value of the third expression is returned. Listing 6.5 uses the ternary operator to set the value of a variable according to the value of $mood.

Listing 6.5. Using the ? Operator
1: <?php
2: $mood = "sad";
3: $text = ($mood == "happy") ? "I'm in a good mood!" : "I am in a $mood mood.";
4: echo "$text";
5: ?>

In line 2, $mood is set to "sad". In line 3, $mood is tested for equivalence to the string "happy". Because this test returns false, the result of the third of the three expressions is returned.

Put these lines into a text file called testtern.php, and place this file in your Web server document root. When you access this script through your Web browser, it produces the following:

I am in a sad mood.

The ternary operator can be difficult to read, but is useful if you are dealing with only two alternatives and want to write compact code.

    Team LiB
    Previous Section Next Section


    JavaScript Editor Javascript source editor     Web programming

    
    remortgage solicitor quote . Affordable PACS Systems