CodeMIRAI
0 XP

if, else and match

2 min read 6 runnable examples Quiz included

if, elseif, else

PHP
<?php
$score = 74;

if ($score >= 90) {
    $grade = "A";
} elseif ($score >= 75) {
    $grade = "B";
} elseif ($score >= 60) {
    $grade = "C";
} else {
    $grade = "F";
}
echo "Score $score is grade $grade\n";

PHP writes elseif as one word (else if also works).

What counts as false

PHP
<?php
$values = [false, 0, 0.0, "", "0", [], null, "false", " ", [0]];
foreach ($values as $v) {
    echo str_pad(json_encode($v), 10), $v ? "truthy" : "falsy", "\n";
}

These are falsy: false, 0, 0.0, "", "0", an empty array, and null. Everything else is truthy, including the string "false" and a string containing a space. The string "0" being falsy surprises almost everyone, so when a value could legitimately be "0", test it explicitly: if ($input !== "").

The alternative syntax, for templates

PHP
<?php $loggedIn = true; $user = "Asha"; ?>
<?php if ($loggedIn): ?>
  <p>Welcome back, <?= $user ?>!</p>
<?php else: ?>
  <p><a href="/login">Sign in</a></p>
<?php endif; ?>

In files that mix HTML and PHP, if (...):, else: and endif; are easier to follow than braces scattered across HTML. <?= $x ?> is short for <?php echo $x; ?>.

switch

PHP
<?php
$day = "Sat";
switch ($day) {
    case "Sat":
    case "Sun":
        echo "Weekend\n";
        break;
    case "Fri":
        echo "Almost the weekend\n";
        break;
    default:
        echo "Weekday\n";
}

switch compares with ==, the loose comparison, and like C it falls through into the next case unless you break.

match (PHP 8)

PHP
<?php
$status = 404;
$message = match ($status) {
    200, 201 => "OK",
    301, 302 => "Redirect",
    404 => "Not found",
    500 => "Server error",
    default => "Unknown status",
};
echo $message, "\n";

$score = 82;
$grade = match (true) {
    $score >= 90 => "A",
    $score >= 75 => "B",
    default => "C",
};
echo "Grade $grade\n";

match is a modern replacement for most switch statements:

switchmatch
comparisonloose ==strict ===
resultruns statementsreturns a value
falling throughyes, without breaknever
no matching casedoes nothingthrows an UnhandledMatchError

match (true) with conditions as the arms is a tidy way to write range checks.

PHP
<?php
$level = "expert";
echo match ($level) {
    "beginner" => "Start with the basics",
    "intermediate" => "Build a project",
};

There's no arm for "expert" and no default, so match refuses to guess and throws an UnhandledMatchError. That's a feature: a forgotten case fails loudly instead of silently doing nothing.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.