Section 4.3. Conditionals


4.3. Conditionals

Since we've been talking about variables, we should also mention conditionals, which, like variables, form a building block in our foundation of PHP development. They alter a script's behavior according to the criteria set in the code. There are three primary elements of conditionals in PHP:

  • if

  • switch

  • ? : : (shorthand for an if statement)

PHP also supports a conditional called a switch statement. The switch statement is useful when you need to take different action based on the contents of a variable that may be set to one of a list of values.

4.3.1. The if Statement

The if statement offers the ability to execute a block of code, if the supplied condition is trUE; otherwise, the code block doesn't execute. The type of condition can be any expression, including tests for nonzero, null, equality, variables, and returned values from functions.

No matter what, every single conditional you create includes a conditional clause. If a condition is true, the code block in curly brackets ({}) is executed. If not, PHP ignores it and moves to the second condition and continues through as many clauses as you write until PHP hits an else, then it automatically executes that block.

Figure 4-2 demonstrates how an if statement works. The else block always needs to come last and be treated as if it's the default action. This is similar to the semicolon (;), which acts as the end of a sentence. Common true conditions are:

  • $var, if $var has a value other than the empty set (0), an empty string, or NULL

  • isset ($var), if $var has any value other than NULL, including the empty set or an empty string

  • trUE or any variation thereof

Figure 4-2. Execution branching based on an expression


We haven't talked about the second bullet point, isset, yet. isset() is a function that checks whether a variable is set. A set variable is one that has a value other than NULL. Table 4-2 shows comparative and logical operators, which can be used in conjunction with parentheses, (), to create more complicated expressions.

The syntax for the if statement is:

 if (conditional expression)   {   block of code;   } 

If the expression in the conditional block evaluates to TRUE, the block of code after it executes. In this example, if the variable $username is set to Admin, a welcome message is printed. Otherwise, nothing happens.

 if ($username=="Admin") {   echo ('Welcome to the admin page.');   } 

The curly brackets aren't needed if you want to execute only one statement, but it's good practice to always use them, as it makes the code easier to read and more resilient to change.

4.3.1.1. The else statement

The else statement (see Example 4-6) provides for a default block of code that executes if the condition returned is FALSE. It must always be part of an if statement, as it doesn't take a conditional itself.

Example 4-6. else and if statements

 if ($username == "Admin"){     echo ('Welcome to the admin page.'); } else {     echo ('Welcome to the user page.'); } 

Remember to close out the code block from the if conditional if you used brackets to start the block of code. Similar to the if block, the else block should also use curly brackets to begin and end the code.

4.3.1.2. The elseif statement

All of this is great except for when you want to test for several conditions at a time. To do this, you can use the elseif statement. It allows for testing of additional conditions until one is found to be true or you hit the else block. Each elseif has its own code block that comes directly after the elseif condition. The elseif must come after the if statement and before an else statement if one exists.

The elseif structure is a little complicated, but Example 4-7 should help you understand it.

Example 4-7. Checking multiple conditions

 if ($username == "Admin"){     echo ('Welcome to the admin page.'); } elseif ($username == "Guest"){     echo ('Please take a look around.'); } else {     echo ("Welcome back, $username."); } 

Here you can check for and take different action based on two values for $username. Then you also have the option to do something else if the $user_name isn't one of the first two.

The next construct builds on the concepts of the if/else statement, but it allows you to efficiently check the results of an expression to many values without having a separate if/else for each value.

4.3.2. The ? Operator

The ? operator is a ternary operator, meaning it takes three operands. It works like an if statement but returns a value from one of the two expressions. The conditional expression determines the value of the expression. A colon (:) is used to separate the expressions:

 {expression} ? return_when_expression_true : return_when_expression_false; 

Example 4-8 tests a value and returns a different string based on it being trUE or FALSE.

Example 4-8. Using the ? operator to create a message

 <?php $logged_in = TRUE; $user = "Admin"; $banner = ($logged_in==TRUE)?"Welcome back $user!":"Please login."; echo "$banner"; ?> 

Example 4-8 produces:

 Welcome back Admin! 

This can be pretty useful for checking errors. Now, let's look at a statement that lets you check an expression against a list of possible values to pick the executable code.

4.3.3. The switch Statement

The switch statement compares an expression to numerous values. It's very common to have an expression, such as a variable, for which you'll want to execute different code for each value stored in the variable. For example, you might have a variable called $action, which may have the values add, modify, and delete. The switch statement makes it easy to define a block of code to execute for each of those values.

To illustrate the difference between using the if statement and switch to test a variable for several values, we'll show you the code for the if statement (in Example 4-9), and then for the switch statement (in Example 4-10).

Example 4-9. Using if to test for multiple values

 if ($action == "ADD") {     echo "Perform actions for adding.";     echo "As many statements as you like can be in each block."; } elseif ($action == "MODIFY") {     echo "Perform actions for modifying."; } elseif ($action == "DELETE") {     echo "Perform actions for deleting."; } 

Example 4-10. Using switch to test for multiple values

 switch ($action) {     case "ADD":         echo "Perform actions for adding.";         echo "As many statements as you like can be in each block.";         break;     case "MODIFY":         echo "Perform actions for modifying.";         break;     case "DELETE":         echo "Perform actions for deleting.";         break; } 

The switch statement works by taking the value after the switch keyword and comparing it to the cases in the order they appear. If no case matches, no code is executed. Once a case matches, the code is executed. The code in subsequent cases also executes until the end of the switch statement or until a break keyword. This is useful for processes that have several sequential steps. If the user has already done some of the steps, he can jump into the process where he left off.

The expression after the switch statement must evaluate to a simple type like a number, integer, or string. An array can be used only if a specific member of the array is referenced as a simple type.


There are numerous ways to tell PHP to not execute cases besides the matching case.

4.3.3.1. Breaking out

If you want only the code in the matching block to execute, you can place a break keyword at the end of that block. When PHP comes across the break keyword, processing jumps to the next line after the entire switch statement. Example 4-11 illustrates how processing works with no break statements.

Example 4-11. What happens when there are no break keywords

 $action="ASSEMBLE ORDER"; switch ($action) {     case "ASSEMBLE ORDER":         echo "Perform actions for order assembly.<br>";     case "PACKAGE":         echo "Perform actions for packing.<br>";     case "SHIP":         echo "Perform actions for shipping.<br>"; }    echo "Perform actions for shipping.<br>"; } ?> 

If the value of $action is "ASSEMBLE ORDER", the result is:

 Perform actions for order assembly. Perform actions for packing. Perform actions for shipping. 

However, if a user had already assembled an order, a value of "PACKAGE" produces the following:

 Perform actions for packing. Perform actions for shipping. 

4.3.3.2. Defaulting

The case statement also provides a way to do something if none of the other cases match, which is similar to the else statement in an if, elseif, else block.

Use DEFAULT: for the switches last case statement, as shown in Example 4-12.

Example 4-12. Using the DEFAULT: statement to generate an error

 switch ($action) {     case "ADD":         echo "Perform actions for adding.";         break;     case "MODIFY":         echo "Perform actions for modifying.";         break;     case "DELETE":         echo "Perform actions for deleting.";         break;     default:         echo "Error: Action must be either ADD, MODIFY, or DELETE."; } 

The switch statement also supports the alternate syntax in which the switch and endswitch keywords define the start and end of the switch instead of the curly braces {}, as shown in Example 4-13.

Example 4-13. Using endswitch to end the switch definition

 switch ($action):     case "ADD":        echo "Perform actions for adding.";        break;     case "MODIFY":        echo "Perform actions for modifying.";        break;     case "DELETE":        echo "Perform actions for deleting.";        break;     default:        echo "Error: Action must be either ADD, MODIFY, or DELETE."; endswitch; 

You've learned that you can have your programs execute different code based on conditions called expressions. The switch statement provides a convenient format for checking the value of an expression against many possible values.



Learning PHP and MySQL
Learning PHP and MySQL
ISBN: 0596101104
EAN: 2147483647
Year: N/A
Pages: 135

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