In PHP, conditional statements are used to perform different actions based on different conditions.
The most common conditional statements in PHP are:
1. If statement:
“`
if (condition) {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
“`
Example:
“`
$age = 18;
if ($age >= 18) {
echo “You are old enough to vote.”;
} else {
echo “You are not old enough to vote.”;
}
“`
2. Elseif statement:
“`
if (condition1) {
// code to be executed if condition1 is true
} elseif (condition2) {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if both condition1 and condition2 are false
}
“`
Example:
“`
$age = 25;
if ($age < 18) { echo "You are not old enough to vote."; } elseif ($age < 25) { echo "You are not old enough to run for president."; } else { echo "You are old enough to run for president."; } ``` 3. Switch statement: ``` switch (variable) { case value1: // code to be executed if variable is value1 break; case value2: // code to be executed if variable is value2 break; default: // code to be executed if variable doesn't match any case } ``` Example: ``` $day = "Wednesday"; switch ($day) { case "Monday": echo "Today is Monday."; break; case "Tuesday": echo "Today is Tuesday."; break; case "Wednesday": echo "Today is Wednesday."; break; default: echo "Today is not a weekday."; } ```