PHP Match
match is a modern PHP expression for matching a value against several alternatives.
What is it?
match is a modern PHP expression for matching a value against several alternatives.
Why do we use it?
It provides concise value mapping and returns a result.
How does it work?
PHP checks the expression against each match arm using strict comparison.
Syntax
$result = match ($value) {
"A" => "Excellent",
default => "Unknown"
};
Example
<?php
$grade = "A";
$message = match ($grade) {
"A" => "Excellent",
"B" => "Good",
default => "Keep Learning"
};
echo $message;
?>
Example Explained
More Examples
<?php $code = 1; $message = match ($code) { 1 => "Success", 2 => "Warning", default => "Unknown" }; echo $message; ?>
⚠️ Important Rules
match is available in modern PHP versions.
❌ Common Mistakes
Using match on an outdated PHP version.
🌍 Real-World Use
Status mapping and clean conditional values.
📝 Practice Exercise
Map A, B, C and D grades to descriptions.
💻 Try It Yourself
Write and run this PHP lesson inside the AIFA Coding Lab.