Topics Control Flow & Functions Conditionals: if/else, switch, match
beginner 12 min read

Conditionals: if/else, switch, match

Master conditional logic with if/else, switch, and the modern match expression.

If/Else

\$score = 85;
if (\$score >= 90) {
echo "A";
} elseif (\$score >= 80) {
echo "B";
} else {
echo "C";
}

Switch

switch (\$day) {
case 1: echo "Mon"; break;
case 2: echo "Tue"; break;
default: echo "Unknown";
}

Match Expression (PHP 8.0+)

\$result = match (\$status) {
200 => "OK",
404 => "Not Found",
500 => "Server Error",
default => "Unknown",
};

Unlike switch, match is an expression (returns a value) and does strict comparison (===).

Examples

<?php
$age = 20;
$status = match(true) {
    $age < 13 => 'Child',
    $age < 20 => 'Teen',
    $age < 65 => 'Adult',
    default => 'Senior',
};
echo $status;

Your Notes

Sign in to take notes for this lesson.

Quiz

Control Flow & Functions Quiz

0 questions

Sign in to take quiz

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.