← Retour au cours: PHP from scratch

Conditionals: if, else and match

Vidéo bientôt disponible

A useful program almost never runs all its lines in order: it decides. If the user typed an age, a message is shown; if stock is zero, a warning appears; if the password is wrong, it is rejected. These decisions are written with conditional structures. In this lesson you will see if, elseif and else, the ternary operator, the null coalescing operator (??) and the match expression, introduced in PHP 8, which is safer and shorter than the old switch. All the code uses declare(strict_types=1), as we have done since week 2.

if, elseif and else

The if structure evaluates a condition in parentheses. If it is true, it runs the block in braces; if not, PHP tries the elseif branches in order and, if none matches, runs the else. Only one block runs: the first whose condition is true. That is why order matters: put the most specific condition first. Remember that in conditions you use === to compare without type conversion, as you learned in the operators lesson.

php
<?php

declare(strict_types=1);

function gradeLabel(int $score): string
{
    if ($score >= 90) {
        return 'excellent';
    } elseif ($score >= 70) {
        return 'good';
    } elseif ($score >= 50) {
        return 'pass';
    } else {
        return 'fail';
    }
}

echo gradeLabel(95), "\n"; // excellent
echo gradeLabel(72), "\n"; // good
echo gradeLabel(10), "\n"; // fail

Ternary and the ?? operator

The ternary operator condition ? a : b is an if in a single expression; use it only when the result fits in a readable line. Even more useful is ??, which returns the left value if it exists and is not null, and the right one otherwise. It is perfect for default values and raises no warning when an array key does not exist. Do not confuse ?? with ?:, which triggers on any falsy value, such as 0 or the empty string.

php
<?php

declare(strict_types=1);

$user = ['name' => 'Ana', 'age' => 0];

$label = $user['age'] >= 18 ? 'adult' : 'minor';
echo $label, "\n";                       // minor

echo $user['city'] ?? 'unknown', "\n";   // unknown (no warning)
echo $user['age'] ?? 18, "\n";           // 0 (the key exists)
echo $user['age'] ?: 18, "\n";           // 18 (0 is falsy)

match: the modern alternative to switch

match compares a value with several options and returns the result, so you can assign it directly to a variable. It differs from switch in three ways: it uses strict comparison (===), it needs no break because there is no fall-through, and if no case matches and there is no default it throws UnhandledMatchError instead of silently continuing. You can group several values in one case by separating them with commas. Each branch is an expression, not a block of statements.

php
<?php

declare(strict_types=1);

function dayType(string $day): string
{
    return match ($day) {
        'sat', 'sun' => 'weekend',
        'mon', 'tue', 'wed', 'thu', 'fri' => 'workday',
        default => 'unknown',
    };
}

echo dayType('sat'), "\n"; // weekend
echo dayType('wed'), "\n"; // workday
echo dayType('xyz'), "\n"; // unknown

// match(true) lets you use conditions as cases
$temp = 31;
$msg = match (true) {
    $temp >= 30 => 'hot',
    $temp >= 15 => 'mild',
    default => 'cold',
};
echo $msg, "\n"; // hot

Testez vos acquis

Question 1 sur 1

What does match do if no case matches and there is no default?

✎ Mes notes

Enregistré seulement dans ce navigateur. Connectez-vous pour le garder dans votre compte.0/5000 caractères

← PrécédenteSuivante →