Switching Flow
Most scripts will evaluate conditions and change their behavior accordingly. These decisions are what make your PHP pages dynamic; that is, able to change their output according to circumstances. Like most programming languages, PHP allows you to do this with an if statement.
The if Statement
An 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 between parentheses. If this expression results in a true value, the statement is executed. Otherwise, the statement is skipped entirely. This enables scripts to make decisions based on any number of factors:
if (
expression ) {
// code to execute if the expression evaluates to true
}
Listing 5.1 executes a block of code only if a variable contains the string "happy".
Listing 5.1 An if Statement
1: <html>
2: <head>
3: <title>Listing 5.1</title>
4: </head>
5: <body>
6: <?php
7: $mood = "happy";
8: if ($mood == "happy") {
9: echo "Hooray, I''m in a good mood";
10: }
11: ?>
12: </body>
13: </html>
You use the comparison operator == to compare the variable $mood with the string "happy". If they match, the expression evaluates to true, and the code block below the if statement is executed.
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 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 the if statement, you will often 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 5.2 amends the example in Listing 5.1 so that a default block of code is executed if $mood is not equivalent to "happy".
Listing 5.2 An if Statement That Uses else
1: <html>
2: <head>
3: <title>Listing 5.2</title>
4: </head>
5: <body>
6: <?php
7: $mood = "sad";
8: if ($mood == "happy") {
9: echo "Hooray, I''m in a good mood";
10: } else {
11: echo "Not happy but $mood";
12: }
13: ?>
14: </body>
15: </html>
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:
Not happy but sad
Notice in line 7 that $mood contains the string "sad", which obviously is not equal to "happy", so the expression in the if statement in line 8 evaluates to false. This results in the first block of code (line 9) being skipped. However, the block of code after else is executed, and the message Not happy but sad is printed to the browser. The string "sad" is the value assigned to the variable $mood.
Using the else clause with the if statement allows scripts to make sophisticated decisions, but your options are currently limited to an either-or branch. PHP allows you to evaluate multiple expressions one after another, as you''ll learn next.
Using the else if Clause with the if Statement
You can use an if...else if...else construct to test multiple expressions before offering a default block of code:
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 first expression does not evaluate to true, the first block of code is ignored. The else if clause then causes another expression to be evaluated. Once again, if this expression evaluates to true, the second 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.
![]() | The elseif clause can also be written as a single word (elseif). The syntax you employ is a matter of taste. |
Listing 5.3 adds an else if clause to the previous example.
Listing 5.3 An if Statement That Uses else and else if
1: <html>
2: <head>
3: <title>Listing 5.3</title>
4: </head>
5: <body>
6: <?php
7: $mood = "sad";
8: if ($mood == "happy") {
9: echo "Hooray, I''m in a good mood";
10: } elseif ($mood == "sad") {
11: echo "Awww. Don''t be down!";
12: } else {
13: echo "Neither happy nor sad but $mood";
14: }
15: ?>
16: </body>
17: </html>
Once again, $mood holds a string, "sad", in line 7. This is not equal to "happy", so the first block in line 9 is ignored. The else if clause in line 10 tests for equivalence between the contents of $mood and the value "sad", which evaluates to true. This block of code is therefore executed. In lines 12, 13, and 14, we provide the default behavior which is invoked if none of the test conditions have been fulfilled. 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 "unknown" and run the script, and it will produce the following:
Neither happy nor sad but unknown
The switch Statement
The switch statement is an alternative way of changing flow according to the evaluation of an expression. Using the if statement in conjunction with else if, you can evaluate multiple expressions. However, a switch statement evaluates only one expression, executing different code according to the result of that expression, for as long as the expression evaluates to a simple type (a number, a string, or a Boolean). The result of an expression evaluated as part of an if statement is read as either true or false, whereas the expression of a switch statement yields a result that is subsequently tested against any number of values:
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. Within the switch statement''s block of code, you find a number of case statements. Each of these cases tests a value against the result of the switch expression. If the case is equivalent to the expression result, the code after 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 evaluated. If the optional default statement is reached, its code is executed.
Listing 5.4 re-creates the functionality of the if statement example, using the switch statement.
Listing 5.4 A switch Statement
1: <html>
2: <head>
3: <title>Listing 5.4</title>
4: </head>
5: <body>
6: <?php
7: $mood = "sad";
8: switch ($mood) {
9: case "happy":
10: echo "Hooray, I''m in a good mood";
11: break;
12: case "sad":
13: echo "Awww. Don''t be down!";
14: break;
15: default:
16: print "Neither happy nor sad but $mood";
17: break;
18: }
19: ?>
20: </body>
21: </html>
Once again, in line 7, the $mood variable is initialized to "sad". The switch statement in line 8 uses this variable as its expression. The first case statement in line 9 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 12. The string "sad" is equivalent to the value of $mood, so this block of code is executed. The break statement in line 14 ends the process. Lines 15 through 17 provide the default action should neither case 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, but 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 5.5 uses the ternary operator to set the value of a variable according to the value of $mood.
Listing 5.5 Using the ? Operator
1: <html>
2: <head>
3: <title>Listing 5.5</title>
4: </head>
5: <body>
6: <?php
7: $mood = "sad";
8: $text = ($mood == "happy") ? "I''m in a good mood" : "Not happy but $mood";
9: echo "$text";
10: ?>
11: </body>
12: </html>
In line 7, $mood is set to "sad". In line 8, $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:
Not happy but sad
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.