PHP If…Else…Elseif Statements
In PHP, you can use if, else, and elseif (or else if) statements to control the flow of your program based on certain conditions. These statements allow you to execute different blocks of code depending on whether a condition evaluates to true or false. Here’s the basic syntax for these statements:
php
if (condition1) {
// Code to be executed if condition1 is true
} elseif (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if both condition1 and condition2 are false
}
Let’s break down the different parts:
- The
if
statement checks a condition and executes the block of code inside the curly braces if the condition is true. - The
elseif
statement allows you to check an additional condition if the precedingif
orelseif
condition(s) evaluate to false. You can have multipleelseif
statements to check different conditions. - The
else
statement is optional and serves as a catch-all block of code to be executed if all the preceding conditions are false. It doesn’t require a condition because it only runs when none of the previous conditions evaluate to true.
Here’s an example that demonstrates the usage of these statements:
php
$age = 25;
if ($age < 18) {
echo "You are underage.";
} elseif ($age >= 18 && $age < 65) {
echo "You are eligible to vote and work.";
} else {
echo "You are eligible for retirement benefits.";
}
In this example, the code checks the value of the $age
variable and prints a corresponding message based on the condition that evaluates to true.
Note that you can nest if…else statements within each other to create more complex conditions and execution flows. However, it’s important to keep the code readable and maintainable by properly indenting and organizing your statements.