PHP match Expression

The match expression introduced in PHP 8.0 provides a concise and predictable way to compare a value against various patterns and execute specific code based on the match. It uses strict comparison (===) and allows returning a value, making it more powerful than the traditional switch statement.

Example 1: Vehicles

Condition: Determine the type of vehicle based on its number of wheels.

 
$vehicle = "motorcycle";
$wheels = match ($vehicle) {
    "car" => 4,
    "motorcycle" => 2,
    "truck" => 6,
    default => throw new Exception("Unknown vehicle type.")
};
 
echo "The $vehicle has $wheels wheels.";
 
 

Explanation:

  • The match expression takes the variable $vehicle as its subject.
  • Each arm of the match expression checks if the subject value matches the specified pattern (string in this case).
  • If a match is found, the corresponding expression (number of wheels) is returned.
  • The default arm is used if none of the previous conditions are met.
  • The output will be: "The motorcycle has 2 wheels."

 

Example 2: Products

Condition: Apply different discounts based on the product category.

 
$category = "electronics";
$discount = match ($category) {
    "electronics" => 0.1,
    "clothing" => 0.2,
    "furniture" => 0.15,
    default => 0,
};
 
echo "The product has a $discount discount.";
 
 

Explanation:

  • The match expression checks the product category stored in $category.
  • Depending on the category, different discount rates are defined in each arm.
  • The final discount value is assigned to the variable $discount.
  • The output will be: "The product has a 0.1 discount."

Example:3

 
function getCategory($item) {
    return match ($item) {
        'car', 'truck', 'motorcycle' => 'Vehicles',
        'laptop', 'phone', 'tablet' => 'Electronics',
        'shirt', 'shoes', 'pants' => 'Clothing',
        default => 'Other'
    };
}
 
echo getCategory('car'); // Outputs: Vehicles
echo getCategory('tablet'); // Outputs: Electronics
echo getCategory('shoes'); // Outputs: Clothing
echo getCategory('lamp'); // Outputs: Other
 
 

The function called getCategory that takes a single argument, $item, and returns the category that the item belongs to.

The getCategory function uses a match statement to compare the value of $item against different patterns and return a corresponding category. Each "case" of the statement specifies a list of acceptable values for $item, and the arrow (=>) separates the pattern from the associated category.