Course Content
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.

The if statement executes a block of code only if the condition is true.

if (condition) {
    // Code to execute if condition is true
}
PHP
<?php
$age = 20;

if ($age >= 18) {
    echo "You are eligible to vote.";
}
?>
  • $age = 20
  • Condition: $age >= 18true
  • Output: You are eligible to vote.

The else block executes when the if condition is false.

if (condition) {
    // Code if condition is true
} else {
    // Code if condition is false
}
PHP
<?php
$marks = 35;

if ($marks >= 40) {
    echo "You passed the exam.";
} else {
    echo "You failed the exam.";
}
?>
  • $marks = 35
  • Condition: $marks >= 40false
  • else block executes → Output: You failed the exam.

The elseif is used when we want to check multiple conditions.

if (condition1) {
    // Code if condition1 is true
} elseif (condition2) {
    // Code if condition2 is true
} else {
    // Code if none of the conditions are true
}
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";
}
?>
  • $percentage = 72
  • Condition 1: $percentage >= 90 → false
  • Condition 2: $percentage >= 75 → false
  • Condition 3: $percentage >= 60 → true
  • Output: Grade: B
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>
  • User enters age.
  • If age >= 60 → Output: Senior Citizen
  • Else if age >= 18 → Output: Adult
  • Else → Output: Minor