if, else and match
if, elseif, else
<?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
$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 $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
$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
$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:
switch | match | |
|---|---|---|
| comparison | loose == | strict === |
| result | runs statements | returns a value |
| falling through | yes, without break | never |
| no matching case | does nothing | throws an UnhandledMatchError |
match (true) with conditions as the arms is a tidy way to write range checks.
<?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.