PHP match statement
Today we will explore this new control structure in PHP called match. We have already seen if and switch, and now we will look at a structure similar to these.
Match performs strict comparisons using ===, which allows us to avoid comparison errors. Additionally, the match expression does not fall through to the next case, so we don’t have to use break statements.
It is also worth noting that the match expression is much cleaner than switch and its result does not necessarily need to be used immediately.
Let’s see its syntax:
like a strict if statement.
Sintaxis / Sintax$return_value = match (subject_expression) { single_conditional_expression => return_expression, };
Multiple conditions with the same return.
Sintaxis / Sintax$return_value = match (subject_expression) { conditional_expression1, conditional_expression2 => return_expression, };
Multiple conditions with different return.
Sintaxis / Sintax$return_value = match (subject_expression) { conditional_expression1 => return_expression, conditional_expression2 => return_expression2, };
Use of default: If none of the above is met, what is in default will be used.
Sintaxis / Sintax$return_value = match (subject_expression) { conditional_expression1 => return_expression, conditional_expression2 => return_expression2, default => return_expresion3, };
PHP match Examples
We can storage the value obtained from a match for later use.
$valor = 2; // Reservamos el resultado del match $mensaje = match($valor) { 1 => 'El valor es uno', 2 => 'El valor es dos', 3 => 'El valor es tres', default => 'El valor no coincide con ninguna opción', }; // Utilizamos el mensaje posteriormente echo $mensaje;
Making an echo call to print on the screen the value returned by match.
$opcion = "B"; echo "Seleccionaste la opción: $opcion\n"; echo match($opcion) { 'A' => 'Opción A seleccionada', 'B' => 'Opción B seleccionada', 'C' => 'Opción C seleccionada', default => 'Opción no válida', };
Multiple conditions with the same return.
$edad = 25; $grupoEdad = match($edad) { 0 => 'Bebé', 1, 2, 3, 4 => 'Niño pequeño', 5, 6, 7, 8, 9, 10 => 'Niño', 11, 12, 13, 14, 15, 16 => 'Adolescente', 17, 18, 19 => 'Joven', default => 'Adulto', }; echo "La persona de $edad años es un $grupoEdad.";
A slightly more complex example, where the advantages of using match are more noticeable.
Ejemplo de matchclass Figura { public string $tipo; public $dimensiones; public function __construct(string $tipo, $dimensiones) { $this->tipo = $tipo; $this->dimensiones = $dimensiones; } public function calcularArea(): float { return match($this->tipo) { 'circulo' => M_PI * pow($this->dimensiones, 2), 'rectangulo' => $this->dimensiones['base'] * $this->dimensiones['altura'], default => 0, }; } } // Crear un círculo con radio 5 $circulo = new Figura('circulo', 5); echo "Área del círculo: " . $circulo->calcularArea() . "\n"; // Crear un rectángulo con base 4 y altura 6 $rectangulo = new Figura('rectangulo', ['base' => 4, 'altura' => 6]); echo "Área del rectángulo: " . $rectangulo->calcularArea() . "\n"; // Caso por defecto, figura desconocida $figuraDesconocida = new Figura('hexagono', 10); echo "Área de figura desconocida: " . $figuraDesconocida->calcularArea() . "\n";