Operators, Conditionals, and PHP Decision-Making - Conditionals
(Page 3 of 4 )
Conditionals, 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 conditionals in PHP:
The switch statement is useful when you have multiple things you want to do and need to take different actions based on the contents of a variable. The switch statement is discussed in more detail later in this chapter.
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 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 braces ({}) is executed. If not, PHP ignores it and moves to the second condition, continuing through all clauses written until PHP hits an else. Then it automatically executes that block only if the IF condition proves to be FALSE; otherwise, it moves on. The curly braces are not required if you have only one line of code to execute in the block. An else statement is not always required.
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 (;). 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 yet about the second bullet point. isset() is a function that checks whether a variable is set. A set variable 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 that follows 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 braces 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.
Next: The else statement >>
More Programming Basics Articles
More By O'Reilly Media
|
This article is excerpted from chapter four of the book Learning PHP and MySQL, Second Edition, written by Michele Davis and Jon Phillips (O'Reilly, 2006; ISBN: 0596101104). Check it out today at your favorite bookstore. Buy this book now.
|
|