PHP if else & if else if
In PHP, the if, else, and else if statements are used to execute different blocks of code based on certain conditions. Here's a breakdown of how each of these control structures works, along with examples.
if Statement
The if statement executes a block of code if a specified condition is true.
Syntax:
if (condition) {
// Code to be executed if the condition is true
}
Example:
$age = 20;
if ($age >= 18) {
echo "You are an adult.";
}
Output:
You are an adult.
if...else Statement
The if...else statement executes one block of code if a condition is true, and another block of code if it is false.
Syntax:
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Example:
$age = 16;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are not an adult.";
}
Output:
You are not an adult.
if...else if...else Statement
The if...else if...else statement allows you to check multiple conditions, executing different blocks of code based on which condition is true.
Syntax:
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 neither condition1 nor condition2 is true
}
Example:
$score = 75;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 80) {
echo "Grade: B";
} elseif ($score >= 70) {
echo "Grade: C";
} else {
echo "Grade: F";
}
Output:
Grade: C
Nested if Statements
You can also nest if statements within each other to create more complex conditions.
Example:
$age = 20;
$is_student = true;
if ($age >= 18) {
if ($is_student) {
echo "You are an adult student.";
} else {
echo "You are an adult.";
}
} else {
echo "You are not an adult.";
}
Output:
You are an adult student.
Summary
if: Executes a block of code if the condition is true.
else: Executes a block of code if the if condition is false.
else if: Checks another condition if the previous if or else if condition is false.
- Nested
if: Allows more complex conditions by placing if statements inside other if statements.
These control structures are fundamental for making decisions in your PHP code based on various conditions.