← Back to Chapters

PHP If Elseif Statement

? PHP If Elseif Statement

? Quick Overview

The if...elseif...else statement in PHP allows checking multiple conditions in sequence. Only the first true condition executes, and the remaining conditions are skipped.

? Key Concepts

  • Conditions are evaluated from top to bottom
  • Only one block executes per decision chain
  • Useful for grading systems, ranges, and decision trees

⚙️ Syntax / Theory

? View Syntax Structure
// PHP if-elseif-else syntax structure
<?php
if (condition1) {
    // Executes when condition1 is true
} elseif (condition2) {
    // Executes when condition2 is true
} else {
    // Executes when all conditions are false
}
?>

? Code Example

? View Code Example
// Determine grade based on marks
<?php
$marks = 75;

if ($marks >= 90) {
    echo "Grade: A";
} elseif ($marks >= 75) {
    echo "Grade: B";
} elseif ($marks >= 60) {
    echo "Grade: C";
} else {
    echo "Grade: F";
}
?>

? Live Output / Explanation

Output

Grade: B

The condition $marks >= 75 evaluates to true, so PHP prints Grade: B and ignores the remaining conditions.

? Live Grade Simulator

Adjust the marks to see how PHP evaluates each condition sequentially.

if ($marks >= 90) { echo "Grade: A"; }
elseif ($marks >= 75) { echo "Grade: B"; }
elseif ($marks >= 60) { echo "Grade: C"; }
else { echo "Grade: F"; }
Result: Grade B
 

? Interactive Logic Flow

This logic works like a vertical decision ladder where PHP stops at the first true condition and exits the chain.

? Use Cases

  • Student grading systems
  • Salary tax slabs
  • Discount calculation
  • User role validation

✅ Tips & Best Practices

  • Order conditions from most specific to least specific
  • Use elseif instead of multiple if blocks
  • Always include an else for fallback handling

? Try It Yourself

  • Create grade_check.php
  • Change the marks value
  • Observe how different grades are displayed