Introduction
The match expression was introduced in PHP 8.0. It allows you to compare a value against multiple possible conditions and return a result for the matching condition. Unlike a traditional switch statement, match uses strict comparison, does not require break, and returns a value that can be stored in a variable. In this chapter, you will practise Match Expressions in PHP Practice questions with solutions to help you build concepts.
Question 1: Display a Day Name Using a Match Expression
Problem Statement
Write a PHP program that stores a number from 1 to 7 and displays the corresponding day of the week using a match expression. Display an error message if the number does not match any valid day.
PHP Solution
<?php
$dayNumber = 3;
$dayName = match ($dayNumber) {
1 => "Monday",
2 => "Tuesday",
3 => "Wednesday",
4 => "Thursday",
5 => "Friday",
6 => "Saturday",
7 => "Sunday",
default => "Invalid day number"
};
echo $dayName;
?>
Sample Output
Wednesday
Explanation
The match expression compares $dayNumber with each listed value. Since the value is 3, it returns "Wednesday" and stores it in $dayName.
If no value matches, the default branch returns "Invalid day number". Unlike switch, a match expression returns a value and does not need break statements.
Concepts Covered
- PHP
matchexpression - Match arms
- Returning values
- Default branch
- Conditional logic
Question 2: Create a Calculator Using a Match Expression
Problem Statement
Write a PHP program that performs addition, subtraction, multiplication, or division based on the selected operator. Use a match expression and handle division by zero.
PHP Solution
<?php
$num1 = 20;
$num2 = 5;
$operator = "/";
$result = match ($operator) {
"+" => $num1 + $num2,
"-" => $num1 - $num2,
"*" => $num1 * $num2,
"/" => $num2 != 0
? $num1 / $num2
: "Cannot divide by zero",
default => "Invalid operator"
};
echo "Result: " . $result;
?>
Sample Output
Result: 4
Explanation
The match expression checks the value of $operator and returns the result of the selected operation.
Here, the operator is /, so PHP divides 20 by 5. The ternary operator checks whether $num2 is not zero before performing division.
If an unsupported operator is provided, the default branch returns "Invalid operator".
Concepts Covered
- Match expressions
- Arithmetic operators
- Ternary operator
- Division-by-zero handling
- Default branch
Question 3: Convert a Month Number into a Month Name
Problem Statement
Create a PHP program that accepts a month number from 1 to 12 and displays the corresponding month name using a match expression. Display a message for an invalid month number.
PHP Solution
<?php
$monthNumber = 10;
$monthName = match ($monthNumber) {
1 => "January",
2 => "February",
3 => "March",
4 => "April",
5 => "May",
6 => "June",
7 => "July",
8 => "August",
9 => "September",
10 => "October",
11 => "November",
12 => "December",
default => "Invalid month number"
};
echo $monthName;
?>
Sample Output
October
Explanation
The variable $monthNumber contains 10. PHP finds the matching arm and returns "October".
The default branch handles values such as 0 or 13. This makes the program more reliable when the input is outside the expected range.
Concepts Covered
- Match expressions
- Numeric matching
- Month mapping
- Default values
- Input validation basics
Question 4: Assign a Grade Based on Marks
Problem Statement
Write a PHP program that assigns a grade based on a student’s marks using a match expression.
Use these rules:
- 90–100: Grade A
- 80–89: Grade B
- 70–79: Grade C
- 60–69: Grade D
- 0–59: Grade F
- Any other value: Invalid marks
PHP Solution
<?php
$marks = 85;
$grade = match (true) {
$marks < 0 || $marks > 100 => "Invalid marks",
$marks >= 90 => "Grade A",
$marks >= 80 => "Grade B",
$marks >= 70 => "Grade C",
$marks >= 60 => "Grade D",
default => "Grade F"
};
echo $grade;
?>
Sample Output
Grade B
Explanation
This example uses match (true), which allows each arm to contain a Boolean condition. PHP evaluates the conditions in order and selects the first one that evaluates to true.
The first condition checks whether the marks are outside the valid range. The remaining conditions check the grade boundaries from highest to lowest.
Because $marks is 85, the program returns "Grade B".
Important: The order of conditions matters. If a broader condition is placed before a more specific one, it may match first and produce an incorrect result.
Concepts Covered
match (true)- Conditional expressions
- Grade calculation
- Logical OR operator
- Input validation
- Condition ordering
Question 5: Display a Message Based on Customer Type
Problem Statement
A company provides different messages to customers based on their membership type:
- Basic: Standard benefits
- Silver: Additional benefits
- Gold: Premium benefits
- Platinum: Exclusive benefits
Write a PHP program that displays the appropriate message using a match expression.
PHP Solution
<?php
$membership = "Gold";
$message = match ($membership) {
"Basic" => "You have standard benefits",
"Silver" => "You have additional benefits",
"Gold" => "You have premium benefits",
"Platinum" => "You have exclusive benefits",
default => "Unknown membership type"
};
echo $message;
?>
Sample Output
You have premium benefits
Explanation
The match expression compares $membership with each membership type.
Since the value is "Gold", PHP returns "You have premium benefits". If the value does not match any listed membership type, the default branch returns "Unknown membership type".
Concepts Covered
- String matching
- Match expressions
- Customer categories
- Returning text values
- Default handling
Question 6: Calculate a Discount Based on Product Category
Problem Statement
A shop offers different discounts depending on the product category:
- Electronics: 10%
- Clothing: 15%
- Grocery: 5%
- Furniture: 20%
Write a PHP program that calculates the discount amount and final price using a match expression.
PHP Solution
<?php
$productCategory = "Furniture";
$price = 5000;
$discountRate = match ($productCategory) {
"Electronics" => 10,
"Clothing" => 15,
"Grocery" => 5,
"Furniture" => 20,
default => null
};
if ($discountRate === null) {
echo "Invalid product category";
} elseif ($price < 0) {
echo "Price cannot be negative";
} else {
$discountAmount = ($price * $discountRate) / 100;
$finalPrice = $price - $discountAmount;
echo "Original Price: " . $price . "\n";
echo "Discount Rate: " . $discountRate . "%\n";
echo "Discount Amount: " . $discountAmount . "\n";
echo "Final Price: " . $finalPrice;
}
?>
Sample Output
Original Price: 5000
Discount Rate: 20%
Discount Amount: 1000
Final Price: 4000
Explanation
The match expression returns the discount percentage based on the product category. Furniture receives a 20% discount.
The program then calculates the discount amount and subtracts it from the original price. If the category is not recognized, the expression returns null, and the program displays an error message instead of calculating a discount.
The negative-price check prevents an invalid price from being used in the calculation.
Concepts Covered
- Match expressions
- Product categories
- Percentage calculations
nullas a default result- Conditional validation
Key Takeaways
- The
matchexpression was introduced in PHP 8.0. - A
matchexpression returns a value that can be stored in a variable. - Each match arm uses the
=>operator to associate a matching value with a result. - Multiple comma-separated values can share one match arm.
- The
defaultarm handles values that do not match any other arm. - Unlike
switch,matchuses strict comparison, so values must match in both value and type. - A
matchexpression does not requirebreakstatements. - If no arm matches and there is no
defaultarm, PHP throws anUnhandledMatchError. match (true)can be used to evaluate Boolean conditions in order.- PHP
matchexpressions are useful for calculators, categories, status messages, discounts, and business rules. - Always validate input before performing calculations or making important decisions.
Frequently Asked Questions (FAQs)
1. What is a match expression in PHP?
A match expression selects a result based on the value of an expression. It compares the value against multiple match arms and returns the result associated with the first matching arm.
2. Which PHP version introduced match expressions?
The match expression was introduced in PHP 8.0. It is not available in PHP 7.x.
3. What is the difference between match and switch in PHP?
A match expression returns a value, uses strict comparison, and does not require break. A switch statement uses loose comparison and typically uses break to prevent execution from continuing into later cases.
4. Does PHP match require a default arm?
No. The default arm is optional. However, if no arm matches and there is no default, PHP throws an UnhandledMatchError.
5. Can a match expression return a string or number?
Yes. A match expression can return strings, integers, floating-point numbers, Boolean values, null, arrays, or other valid PHP expressions.
6. Can multiple values use the same match arm?
Yes. Separate values with commas. For example, "admin", "manager" => "Full access" returns the same result for either role.
7. What does strict comparison mean in a match expression?
Strict comparison means PHP checks both the value and its data type. For example, integer 1 and string "1" are not considered equal by a match expression.
8. Can we use conditions inside match expressions?
Yes. You can use match (true) and provide Boolean conditions as match arms. PHP evaluates them in order and selects the first condition that evaluates to true.
9. Do match expressions need break statements?
No. Each match arm produces a result, and PHP does not continue executing the following arms. Therefore, break statements are unnecessary.
10. When should I use match instead of if-else?
Use match when selecting one result from several possible values. Use if-else when you need more flexible branching, execute multiple statements in a branch, or perform more complicated conditional logic.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
