Sobes.tech
Junior — Middle

Can you explain what the match() function does in PHP 8 and how it differs from the switch statement?

sobes.tech AI

Answer from AI

In PHP 8, the match() function is an expression that allows comparing a value with multiple options and returning a result. It is similar to the switch construct but has several differences:

  • match returns a value, meaning it is an expression, not an operator.
  • In match, the comparison is strict (===), whereas in switch, it is loose (==).
  • In match, there is no need to use break to prevent "fall-through".
  • match requires all options to be covered; otherwise, an exception will be thrown.

Example of using match:

$status = 2;
$message = match($status) {
    1 => 'Waiting',
    2 => 'In progress',
    3 => 'Completed',
    default => 'Unknown status',
};
echo $message; // Outputs: In progress

Thus, match is convenient for clean and safe value matching with results.

Can you explain what the match() function does in PHP… - sobes.tech