Conditional statements in PHP allow us to execute different code blocks based on certain conditions.
There are several types of conditional statements in PHP:
1. if statement: The if statement is the most basic type of conditional statement. It checks a condition and if the condition is true, it executes a block of code. For example:
“`php
if ($age >= 18) {
echo “You are an adult”;
}
“`
2. if…else statement: The if…else statement allows us to execute different code blocks depending on the condition. If the condition is true, it executes the code block inside the “if” statement. If the condition is false, it executes the code block inside the “else” statement. For example:
“`php
if ($age >= 18) {
echo “You are an adult”;
} else {
echo “You are not an adult”;
}
“`
3. if…elseif…else statement: The if…elseif…else statement allows us to test multiple conditions and execute different code blocks based on the conditions. For example:
“`php
if ($score >= 80) {
echo “You got an A”;
} elseif ($score >= 70) {
echo “You got a B”;
} elseif ($score >= 60) {
echo “You got a C”;
} else {
echo “You did not pass”;
}
“`
4. switch statement: The switch statement is used to perform different actions based on different conditions. It evaluates an expression and executes the code block that matches the value of the expression. For example:
“`php
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 Monday, Tuesday, or Wednesday”;
}
“`
In addition to these conditional statements, there are also comparison operators (e.g., ==, !=, <, >, <=, >=) and logical operators (e.g., &&, ||, !) that can be used to test conditions in PHP.