PHP Match

PHP Match Expression

Introduced in PHP 8.0, the match expression provides a shorter, safer, and faster alternative to the switch statement.


Match vs. Switch

There are three main differences between match and switch:

  1. Strict Comparison: match does a strict type comparison (===), whereas switch does a loose comparison (==).
  2. No Break Required: match automatically breaks execution when it finds a matching block, preventing "fall-through" errors.
  3. Returns a Value: The match expression returns a value, meaning you can assign its result directly to a variable.

Match Example

<?php
$status = 200;

$message = match ($status) { 200, 201 => 'Success!', 400, 404 => 'Bad Request!', 500 => 'Server Error!', default => 'Unknown Status', };

echo $message; ?>