Match
PHP Control Structures: Match
		
		Categories:
Examples
Basic
$name = match(2) {
    1 => 'One',
    2 => 'Two',
    default => echo 'Unknown: ' . $name,
};
echo $name; // "Two"
Multiple matching conditions
match($request_method) {
    'post' => $this->handlePost(),
    'get', 'head' =>  $this->handleGet(),
};
Strict matches without type coercion
function read(mixed $key): string {
    return match ($key) {
        1 => 'Integer 1',
        '1' => 'String 1',
        true => 'Bool true',
        [] => 'Empty array',
        [1] => 'Array [1]',
    };
}
read(1); // "Integer 1"
read('1'); // "String 1"
read(true); // "Bool true"
Error Example
Multiple expression
// ERROR
match($name) {
    'foo' => 
        initFoo();
        processFoo();
};
No match
// Fatal error: Uncaught UnhandledMatchError in ...
value = 3;
match($value) {
    1 => 'One',
    2 => 'Two',
};
match vs switch
| switch | match | |
|---|---|---|
| Requires PHP ^8.0 | No | Yes | 
| Returns value | No | Yes | 
| default condition support | Yes | Yes | 
| Multiple conditions in single arm | Yes | Yes | 
| Multiple expressions in code block | Yes | No | 
| Implicit break | No | Yes | 
| Falls-through without break | Yes | No | 
| Throws an exception on no matches | No | Yes | 
| Match against arbitrary expressions | Yes | Yes | 
| Strict type-safe comparison | No | Yes |