4.3. ConditionalsSince 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:
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 StatementThe 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:
Figure 4-2. Execution branching based on an expressionWe 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 statementThe 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
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 statementAll 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
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 ? OperatorThe ? 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
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 StatementThe 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
Example 4-10. Using switch to test for multiple values
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.
There are numerous ways to tell PHP to not execute cases besides the matching case. 4.3.3.1. Breaking outIf 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
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. DefaultingThe 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
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
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. |