Match Expression in PHP 8

The match expression is a new feature introduced in PHP 8 that provides a more concise and type-safe alternative to switch-case statements. Unlike switch statements, match expressions perform strict comparisons and return values directly.

Key Differences from Switch Statements

  • Match expressions use strict comparison (===) instead of loose comparison (==)

  • No need for break statements − execution doesn't fall through

  • Returns a value that can be assigned to variables or used in expressions

  • Supports multiple conditions with comma separation

Example: PHP 7 Switch Statement Behavior

In PHP 7, switch statements use loose comparison, which can lead to unexpected results ?

<?php
   switch (1.0) {
      case '1.0':
         $result = "Hello World!";
         break;
      case 1.0:
         $result = "Looks good";
         break;
   }
   echo $result;
?>
Hello World!

Example: PHP 8 Match Expression with Strict Comparison

The same logic using match expression performs strict comparison ?

<?php
   echo match (1.0) {
      '1.0' => "Hello World!",
      1.0 => "Looks Good!",
   };
?>
Looks Good!

Example: Simple Match Expression

Match expressions can be used for clean value mapping ?

<?php
   echo match (2) {
      1 => 'Company',
      2 => 'Department',
      3 => 'Employee',
   };
?>
Department

Example: Multiple Conditions

Match expressions support multiple conditions separated by commas ?

<?php
   $status = 'pending';
   
   echo match ($status) {
      'new', 'pending' => 'In Progress',
      'approved' => 'Completed',
      'rejected' => 'Failed',
      default => 'Unknown'
   };
?>
In Progress

Conclusion

Match expressions provide a safer and more concise alternative to switch statements with strict type checking and direct value returns. They're particularly useful for simple value mapping and conditional assignments.

Updated on: 2026-03-15T09:42:38+05:30

857 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements