9 of 410 menu

The match Construct

The match construct was introduced in PHP 8.0 and provides a more concise and safer way of branching compared to switch. It takes an expression for comparison and returns the value of the first matching condition. Unlike switch, match performs strict comparison (===) and does not require break.

Syntax

$result = match ($value) { condition1 => result1, condition2 => result2, ... default => default_result };

Example

Simple number matching:

<?php $res = match (2) { 1 => 'One', 2 => 'Two', 3 => 'Three', default => 'Unknown' }; echo $res; ?>

Code execution result:

'Two'

Example

Matching with multiple conditions:

<?php $age = 25; $res = match (true) { $age < 18 => 'Child', $age >= 18 && $age < 65 => 'Adult', $age >= 65 => 'Senior' }; echo $res; ?>

Code execution result:

'Adult'

Example

Usage with arrays:

<?php $arr = [1, 2, 3]; $res = match ($arr) { [1, 2, 3] => 'First sequence', [4, 5, 6] => 'Second sequence', default => 'Other sequence' }; echo $res; ?>

Code execution result:

'First sequence'

See Also

  • the switch operator,
    which provides an alternative way of branching
  • the if function,
    which performs conditional statements
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline