PHP If Else Example

Conditional logic with if, elseif and else in PHP. Edit the code below and press Run to execute it with real PHP in your browser.

Code Editor
Output
Grade: B

How this if else example works

Conditions are checked from top to bottom and only the first true branch runs. Because 85 is not >= 90 but is >= 80, the script prints "Grade: B". PHP spells it elseif (one word), though else if also works with braces.

Ternary, null coalescing and match

Short alternatives for simple conditions. match (PHP 8.0+) compares strictly and returns a value.

<?php
$age = 20;
echo ($age >= 18 ? "adult" : "minor") . "\n";

$input = [];
echo ($input["name"] ?? "guest") . "\n";

$score = 85;
echo match (true) {
    $score >= 90 => "A",
    $score >= 80 => "B",
    default => "C or lower",
} . "\n";

Output:

adult
guest
B