About Lesson
if, else, elseif in PHP
structures allow us to control the flow of the program based on conditions.
In PHP, the most common conditional statements are if, else, and elseif.
1. if Statement:
The if
statement executes a block of code only if the condition is true.
Syntax:
if (condition) {
// Code to execute if condition is true
}
Example:
PHP
<?php
$age = 20;
if ($age >= 18) {
echo "You are eligible to vote.";
}
?>
Explanation:
$age = 20
- Condition:
$age >= 18
→ true - Output:
You are eligible to vote.
2. if…else Statement:
The else
block executes when the if
condition is false.
Syntax:
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
Example:
PHP
<?php
$marks = 35;
if ($marks >= 40) {
echo "You passed the exam.";
} else {
echo "You failed the exam.";
}
?>
Explanation:
$marks = 35
- Condition:
$marks >= 40
→ false else
block executes → Output:You failed the exam.
3. if…elseif…else Statement:
The elseif
is used when we want to check multiple conditions.
Syntax:
if (condition1) {
// Code if condition1 is true
} elseif (condition2) {
// Code if condition2 is true
} else {
// Code if none of the conditions are true
}
Example:
PHP
<?php
$percentage = 72;
if ($percentage >= 90) {
echo "Grade: A+";
} elseif ($percentage >= 75) {
echo "Grade: A";
} elseif ($percentage >= 60) {
echo "Grade: B";
} elseif ($percentage >= 40) {
echo "Grade: C";
} else {
echo "Fail";
}
?>
Explanation:
$percentage = 72
- Condition 1:
$percentage >= 90
→ false - Condition 2:
$percentage >= 75
→ false - Condition 3:
$percentage >= 60
→ true - Output:
Grade: B
Example with HTML + PHP
PHP
<!DOCTYPE html>
<html>
<head>
<title>If-Else Example</title>
</head>
<body>
<form method="post">
Enter your age: <input type="number" name="age">
<button type="submit">Check</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$age = $_POST['age'];
if ($age >= 60) {
echo "You are a Senior Citizen.";
} elseif ($age >= 18) {
echo "You are an Adult.";
} else {
echo "You are a Minor.";
}
}
?>
</body>
</html>
Explanation:
- User enters age.
- If
age >= 60
→ Output: Senior Citizen - Else if
age >= 18
→ Output: Adult - Else → Output: Minor