Control Flow Lesson 7 of 17
PHP if, else, switch and match
Make decisions in PHP with if, elseif and else, switch, and the modern match expression, with grade descriptors and a store menu.
PHP decides what to show with if, elseif, else, switch, and the newer, safer match expression (PHP 8).
if, elseif, else
<?php
$grade = 87;
if ($grade >= 90) {
$descriptor = "Outstanding";
} elseif ($grade >= 85) {
$descriptor = "Very Satisfactory";
} elseif ($grade >= 80) {
$descriptor = "Satisfactory";
} elseif ($grade >= 75) {
$descriptor = "Fairly Satisfactory";
} else {
$descriptor = "Did Not Meet Expectations";
}
echo "$grade: $descriptor";
Output
87: Very Satisfactory
PHP writes elseif as one word (else if also works). Only the first true branch runs.
Conditions in HTML templates
<?php $stock = 0; ?>
<?php if ($stock > 0): ?>
<button>Add to cart</button>
<?php else: ?>
<p class="sold-out">Sold out</p>
<?php endif; ?>
HTML output
<p class="sold-out">Sold out</p>
The colon syntax with endif keeps HTML-heavy pages readable.
switch
<?php
$day = "Fri";
switch ($day) {
case "Mon":
echo "Flag ceremony";
break;
case "Fri":
echo "Coding club";
break;
case "Sat":
case "Sun":
echo "Weekend!";
break;
default:
echo "Regular class";
}
Output
Coding club
match (PHP 8)
<?php
$choice = 2;
$item = match ($choice) {
1 => "Pandesal",
2 => "Kape",
3 => "Itlog",
default => "Unknown",
};
echo "You chose $item";
Output
You chose Kape
matchreturns a value, uses strict comparison (===), and never falls through.- Several values can share an arm:
"Sat", "Sun" => "Weekend". - If nothing matches and there's no
default, PHP throws an error, so mistakes don't go unnoticed.
match with ranges
<?php
function descriptor(int $g): string {
return match (true) {
$g >= 90 => "Outstanding",
$g >= 85 => "Very Satisfactory",
$g >= 80 => "Satisfactory",
$g >= 75 => "Fairly Satisfactory",
default => "Did Not Meet Expectations",
};
}
foreach ([95, 86, 70] as $g) {
echo "$g: " . descriptor($g) . "\n";
}
Output
95: Outstanding 86: Very Satisfactory 70: Did Not Meet Expectations
match (true) picks the first arm whose condition is true, a neat trick for ranges.
Combining conditions
<?php
$age = 67;
$isPwd = false;
$total = 500;
if ($age >= 60 || $isPwd) {
$total *= 0.80;
echo "Senior/PWD discount applied. ";
}
echo "Total: ₱" . number_format($total, 2);
Output
Senior/PWD discount applied. Total: ₱400.00
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04