Switching Flow

Most scripts evaluate conditions and change their behavior accordingly. The capability to make decisions makes your PHP pages dynamic, 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:     print "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" and run the script, the expression in the if statement evaluates to false, and the code block is skipped. The script remains silent.

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:     print "Hooray, I'm in a good mood";  10: } else {  11:     print "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 is not equal to "happy", so the expression in the if statement in line 8 evaluates to false. This means that the first block of code (line 9) is skipped. The block of code after else is executed, and the message "Not happy but sad" is printed to the browser.

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.

Using the elseif Clause with the if Statement

You can use an if...elseif...else construct to test multiple expressions before offering a default block of code:

 if ( expression ) {    // code to execute if the expression evaluates to true } elseif (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 elseif 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 elseif clauses as you want, and if you don't need a default action, you can omit the else clause.

graphics/book.gif

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


Listing 5.3 adds an elseif clause to the previous example.

Listing 5.3 An if Statement That Uses else and elseif
   1: <html>   2: <head>   3: <title>Listing 5.3</title>   4: </head>   5: <body>   6: <?php   7: $mood = "sad";   8: if ( $mood == "happy" ) {   9:     print "Hooray, I'm in a good mood";  10: } elseif ( $mood == "sad" ) {  11:     print "Awww. Don't be down!";  12: } else {  13:     print "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 elseif 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 default behavior. If none of the test conditions have been fulfilled, we simply print out 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 program flow according to the evaluation of an expression. There are some key differences between the switch and if statements. Using the if statement in conjunction with elseif, you can evaluate multiple expressions. The switch statement evaluates only one expression, executing different code according to the result of that expression, 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. The expression of a switch statement yields a result that is 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 switch statement's expression is often simply a variable. Within the switch statement's block of code, you find a number of case statements. Each of these tests a value against the result of the switch statement's expression. If these are equivalent, the code after the case statement is executed. The break statement ends execution of the switch statement altogether. If this is left out, the next case statement's expression is evaluated. If the optional default statement is reached, its code is executed.

graphics/clock.gif

Don't forget to include a break statement at the end of any code that will be executed as part of a case statement. Without break, the program flow will continue to the next case statement and ultimately to the default statement. In most cases, this will not be the behavior that you are expecting.


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:         print "Hooray, I'm in a good mood";  11:         break;  12:     case "sad":  13:         print "Awww. Don't be down!";  14:         break;  15:     default:  16:         print "Neither happy nor sad but $mood";  17: }  18: ?>  19: </body>  20: </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.

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 with the second break statement commented out. 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." Which expression is used to generate the value returned 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: print "$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 like to write compact code.



Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
Sams Teach Yourself PHP, MySQL and Apache in 24 Hours
ISBN: 067232489X
EAN: 2147483647
Year: 2005
Pages: 263

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net