PHP CHAPTER 17

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

PHP Syntax
$result = match ($value) {
    "A" => "Excellent",
    default => "Unknown"
};
💻

Example

PHP Example
<?php

$grade = "A";

$message = match ($grade) {
    "A" => "Excellent",
    "B" => "Good",
    default => "Keep Learning"
};

echo $message;

?>
🔍

Example Explained

The grade A matches the first arm and returns Excellent.
🚀

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.

Open Coding Lab →