PHPPHP
BeginnerLesson 3 of 16

Conditions, ?? and match – PHP

if/elseif, ternary, null coalescing and the modern match expression.

if, elseif and else work like in other languages. The condition goes in parentheses, the block in curly braces.

<?php
$punkte = 73;
if ($punkte >= 90) {
    $note = "excellent";
} elseif ($punkte >= 70) {
    $note = "good";
} else {
    $note = "needs improvement";
}
echo $note, "\n";

Shorthand forms: the ternary operator, ?? (null coalescing) and ?: (Elvis). The spaceship operator <=> returns -1, 0 or 1 and is perfect for sorting.

<?php
$alter = 20;
echo $alter >= 18 ? "adult" : "minor", "\n";

$eingabe = null;
echo $eingabe ?? "Default", "\n";     // Default (only if null / unset)
$name = "";
echo ($name ?: "anonymous"), "\n";        // anonymous (also for empty, 0, false)

echo 5 <=> 3, 3 <=> 3, 1 <=> 2, "\n";  // 10-1

match is the modern replacement for long switch blocks: it is an expression (returns a value), compares strictly (===) and needs no break.

<?php
$status = 404;
$text = match ($status) {
    200, 201 => "OK",
    301 => "Redirected",
    404 => "Not found",
    default => "Unknown",
};
echo $text, "\n";

$n = 7;
echo match (true) {
    $n < 5 => "small",
    $n < 10 => "medium",
    default => "large",
}, "\n";
WarningIf no branch of a match matches and there is no default, PHP throws an UnhandledMatchError. This is intentional: forgotten cases show up immediately. switch, on the other hand, compares loosely (==) and "falls through" if break is missing.
Tip$a ??= "x"; only assigns if $a is still null or unset – ideal for default values.