The match expression helps you choose a value based on a condition, like a smarter and cleaner switch-case. It makes your code easier to read and write.
0
0
Match expression (PHP 8)
Introduction
When you want to select a value based on a variable's value.
When you need a simpler alternative to multiple if-else statements.
When you want to return a value directly from conditions.
When you want to avoid forgetting break statements in switch cases.
When you want to write clearer and less error-prone conditional code.
Syntax
PHP
match (expression) {
value1 => result1,
value2, value3 => result2,
default => defaultResult,
};The match expression returns a value directly.
It uses strict comparison (===), so types must match exactly.
Examples
Returns a message based on the color value.
PHP
$result = match ($color) {
'red' => 'Stop',
'yellow' => 'Caution',
'green' => 'Go',
default => 'Unknown color',
};Uses conditions inside match by matching true, to assign a grade message.
PHP
$grade = 85; $message = match (true) { $grade >= 90 => 'Excellent', $grade >= 75 => 'Good', $grade >= 60 => 'Pass', default => 'Fail', };
Groups multiple values to the same result.
PHP
$day = 3; $dayName = match ($day) { 1, 7 => 'Weekend', 2, 3, 4, 5, 6 => 'Weekday', default => 'Invalid day', };
Sample Program
This program uses a match expression to print a message based on the score value.
PHP
<?php $score = 72; $message = match (true) { $score >= 90 => 'Great job!', $score >= 70 => 'Good effort!', $score >= 50 => 'You passed.', default => 'Try again.', }; echo $message;
OutputSuccess
Important Notes
Match expressions use strict comparison (===), so '1' (string) and 1 (int) are different.
Every match arm must return a value; no fall-through like switch.
Match expressions always return a value, so you can assign them directly to variables.
Summary
Match expressions simplify choosing values based on conditions.
They return values directly and use strict comparison.
They help write cleaner and less error-prone code than switch-case.