Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

Keyword match

Choose a result by strict identity with the subject.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

match ($subject) { $key => $result, default => $fallback }

Choose a result by strict identity with the subject. Only the matching arm result is evaluated and no fallthrough occurs. Without a matching arm or default, PHP throws UnhandledMatchError. Multiple keys can share one result.

function label($v){return match($v){1,2=>"int","1"=>"text"};}
echo json_encode([label(1),label("1")]),PHP_EOL;
try{label(3);}catch(UnhandledMatchError $e){echo get_class($e);}
["int","text"]
UnhandledMatchError

Examples

<?php
function label($v){return match($v){1,2=>"int","1"=>"text"};}
echo json_encode([label(1),label("1")]),PHP_EOL;
try{label(3);}catch(UnhandledMatchError $e){echo get_class($e);}

Result

["int","text"]
UnhandledMatchError

Sources