Branching Statements
Branching statements (conditionals) enable a PHP script to select from among different branches (or blocks of code) in the program's execution.
Contents |
The if statement
if (conditional expression) { // If this expression evaluates to TRUE
block of code; // This block of code is executed; otherwise it is skipped
}
- The (optional) else clause is executed when the conditional expression is FALSE.
if (conditional expression) { // If this expression evaluates to TRUE
block of code; // This block of code is executed.
}
else {
another block of code; // This block is executed if the expression is FALSE
}
- Examples
$n = 55;
if ($n % 5 == 0) {
echo "$n is divisible by 5";
}
else {
echo "$n is NOT divisible by 5";
}
if ($n % 10 == 5 && $n * 2 < 100) {
echo "$n is divisible by 5 and its value doubled is less than 100 ";
}
else {
echo "Either $n is NOT divisible by 5 or its value doubled is not less than 100";
}
The elseif statement
The elseif statement lets you combine a number of unique alternatives into a single statement.
if ($username == "Admin"){
echo "Welcome to the admin page";
}
elseif ($username == "Guest") {
echo "Welcome. Have a look around";
}
else {
echo "Welcome back, $username";
}
The ternary ? operator
The ? operator is like an if statement except it returns a value from one of the two expressions depending on the value of its conditional:
(conditional expression) ? return_if_true : return if false ; $logged_in = TRUE; $user = "Admin"; $banner = ($logged_in==TRUE) ? "Welcome back, $user!" : "Please login"; echo $banner;
The switch statement
The switch statement provides a multiway selection structure. Depending on the value of a variable, one of several branches is selected. It requires the use of the break statement.
switch ($username) {
case "Admin":
echo "Welcome to the Admin page";
break;
case "Guest":
echo "Welcome. Have a look around";
break;
default:
echo "Welcome back, $username";
}
Exercise
Write a switch statement that adds, subtracts, multiplies, or divides x using the action variable. Click here for a solution.
