agyanadda@gmail.com

PHP if else

Operators and Control Flow 1 min read Updated Dec 1, 2026 Topic 12 of 36
if ($marks >= 75) {
    $grade = 'Distinction';
} elseif ($marks >= 60) {
    $grade = 'First';
} elseif ($marks >= 33) {
    $grade = 'Pass';
} else {
    $grade = 'Fail';
}
  • if runs when the condition is true
  • elseif checks the next condition
  • else runs when nothing above matched
  • Only the first true block runs

Combine conditions

if ($age >= 18 && $hasAadhaar) { ... }

Alternative syntax for HTML

In template files, this style is easier to read:

<?php if ($loggedIn): ?>
  <a href="/logout">Logout</a>
<?php else: ?>
  <a href="/login">Login</a>
<?php endif; ?>

Laravel Blade turns this into @if ... @else ... @endif.

Example

Example — Grade and scholarship checker PHP
<?php
$students = ['Asha' => 91, 'Ravi' => 68, 'Aman' => 29, 'Neha' => 77];

foreach ($students as $name => $marks) {
    if ($marks >= 75) {
        $grade = 'Distinction';
    } elseif ($marks >= 60) {
        $grade = 'First Division';
    } elseif ($marks >= 33) {
        $grade = 'Pass';
    } else {
        $grade = 'Fail';
    }

    $scholarship = ($marks >= 90) ? ' – Scholarship!' : '';
    echo "$name ($marks): $grade$scholarship<br>";
}
?>

<?php $loggedIn = true; ?>
<?php if ($loggedIn): ?>
  <p>Welcome back! <a href="#">Logout</a></p>
<?php else: ?>
  <p><a href="#">Login</a></p>
<?php endif; ?>

Output: Asha (91): Distinction – Scholarship! / Ravi (68): First Division / Aman (29): Fail / Neha (77): Distinction / Welcome back! Logout

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which keyword checks another condition after if?

Exercise 2 True / False

In an if/elseif chain, more than one block can run.

Exercise 3 Fill in the Blank

The alternative syntax ends an if block with ___;

Frequently Asked Questions

Yes, with curly braces it works the same as elseif. With the colon (alternative) syntax you must write elseif as one word.