match

(PHP 8)

The match expression branches evaluation based on an identity check of a value. Similarly to a switch statement, a match expression has a subject expression that is compared against multiple alternatives. Unlike switch, it will evaluate to a value much like ternary expressions. Unlike switch, the comparison is an identity check (===) rather than a weak equality check (==). Match expressions are available as of PHP 8.0.0.

Beispiel #1 Structure of a match expression

<?php
$return_value 
match (subject_expression) {
    
single_conditional_expression => return_expression,
    
conditional_expression1conditional_expression2 => return_expression,
};
?>

Beispiel #2 Basic match usage

<?php
$food 
'cake';

$return_value match ($food) {
    
'apple' => 'This food is an apple',
    
'bar' => 'This food is a bar',
    
'cake' => 'This food is a cake',
};

var_dump($return_value);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

string(19) "This food is a cake"

Hinweis: The result of a match expression does not need to be used.

Hinweis: A match expression must be terminated by a semicolon ;.

The match expression is similar to a switch statement but has some key differences:

  • A match arm compares values strictly (===) instead of loosely as the switch statement does.
  • A match expression returns a value.
  • match arms do not fall-through to later cases the way switch statements do.
  • A match expression must be exhaustive.

As switch statements, match expressions are executed match arm by match arm. In the beginning, no code is executed. The conditional expressions are only evaluated if all previous conditional expressions failed to match the subject expression. Only the return expression corresponding to the matching conditional expression will be evaluated. For example:

<?php
$result 
match ($x) {
    
foo() => ...,
    
$this->bar() => ..., // $this->bar() isn't called if foo() === $x
    
$this->baz => beep(), // beep() isn't called unless $x === $this->baz
    // etc.
};
?>

match expression arms may contain multiple expressions separated by a comma. That is a logical OR, and is a short-hand for multiple match arms with the same right-hand side.

<?php
$result 
match ($x) {
    
// This match arm:
    
$a$b$c => 5,
    
// Is equivalent to these three match arms:
    
$a => 5,
    
$b => 5,
    
$c => 5,
};
?>

A special case is the default pattern. This pattern matches anything that wasn't previously matched. For example:

<?php
$expressionResult 
match ($condition) {
    
1=> foo(),
    
3=> bar(),
    default => 
baz(),
};
?>

Hinweis: Multiple default patterns will raise a E_FATAL_ERROR error.

A match expression must be exhaustive. If the subject expression is not handled by any match arm an UnhandledMatchError is thrown.

Beispiel #3 Example of an unhandled match expression

<?php
$condition 
5;

try {
    
match ($condition) {
        
1=> foo(),
        
3=> bar(),
    };
} catch (\
UnhandledMatchError $e) {
    
var_dump($e);
}
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

object(UnhandledMatchError)#1 (7) {
  ["message":protected]=>
  string(33) "Unhandled match value of type int"
  ["string":"Error":private]=>
  string(0) ""
  ["code":protected]=>
  int(0)
  ["file":protected]=>
  string(9) "/in/ICgGK"
  ["line":protected]=>
  int(6)
  ["trace":"Error":private]=>
  array(0) {
  }
  ["previous":"Error":private]=>
  NULL
}

Using match expressions to handle non identity checks

It is possible to use a match expression to handle non-identity conditional cases by using true as the subject expression.

Beispiel #4 Using a generalized match expressions to branch on integer ranges

<?php

$age 
23;

$result match (true) {
    
$age >= 65 => 'senior',
    
$age >= 25 => 'adult',
    
$age >= 18 => 'young adult',
    default => 
'kid',
};

var_dump($result);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

string(11) "young adult"

Beispiel #5 Using a generalized match expressions to branch on string content

<?php

$text 
'Bienvenue chez nous';

$result match (true) {
    
str_contains($text'Welcome') || str_contains($text'Hello') => 'en',
    
str_contains($text'Bienvenue') || str_contains($text'Bonjour') => 'fr',
    
// ...
};

var_dump($result);
?>

Das oben gezeigte Beispiel erzeugt folgende Ausgabe:

string(2) "fr"

Hier Kannst Du einen Kommentar verfassen


Bitte gib mindestens 10 Zeichen ein.
Wird geladen... Bitte warte.
* Pflichtangabe
Es sind noch keine Kommentare vorhanden.

PHP cURL-Tutorial: Verwendung von cURL zum Durchführen von HTTP-Anfragen

cURL ist eine leistungsstarke PHP-Erweiterung, die es Ihnen ermöglicht, mit verschiedenen Servern über verschiedene Protokolle wie HTTP, HTTPS, FTP und mehr zu kommunizieren. ...

TheMax

Autor : TheMax
Kategorie: PHP-Tutorials

Midjourney Tutorial - Anleitung für Anfänger

Über Midjourney, dem Tool zur Erstellung digitaler Bilder mithilfe von künstlicher Intelligenz, gibt es ein informatives Video mit dem Titel "Midjourney Tutorial auf Deutsch - Anleitung für Anfänger" ...

Mike94

Autor : Mike94
Kategorie: KI Tutorials

Grundlagen von Views in MySQL

Views in einer MySQL-Datenbank bieten die Möglichkeit, eine virtuelle Tabelle basierend auf dem Ergebnis einer SQL-Abfrage zu erstellen. ...

admin

Autor : admin
Kategorie: mySQL-Tutorials

Tutorial veröffentlichen

Tutorial veröffentlichen

Teile Dein Wissen mit anderen Entwicklern weltweit

Du bist Profi in deinem Bereich und möchtest dein Wissen teilen, dann melde dich jetzt an und teile es mit unserer PHP-Community

mehr erfahren

Tutorial veröffentlichen

Daten einer Abfrage mit Hilfe von Thumbnails nebeneinander ausgeben

Also den Fehler habe ich gefunden und abgestellt. Warum soll ich float meiden?

Geschrieben von Malchor am 17.05.2024 20:54:01
Forum: PHP Developer Forum
Daten einer Abfrage mit Hilfe von Thumbnails nebeneinander ausgeben

Dein HTML-Code ist definitiv kaputt und float solltest du auch vergessen. Beschäftige dich mit Flex-Box oder Grid

Geschrieben von scatello am 17.05.2024 20:43:50
Forum: PHP Developer Forum
Daten einer Abfrage mit Hilfe von Thumbnails nebeneinander ausgeben

Da ich viele unterschiedliche Tabellen benötige mache ich das so umständlich. Aber ist das der Grund warum das Floaten nicht funktioniert?

Geschrieben von Malchor am 17.05.2024 17:15:03
Forum: PHP Developer Forum
Daten einer Abfrage mit Hilfe von Thumbnails nebeneinander ausgeben

Du möchtest dir bestimmt mal ansehen, wie eine HTML-Tabelle richtig aufgebaut wird: https://www.w3schools.com/tags/tag_th.asp align solltest du ...

Geschrieben von scatello am 17.05.2024 17:12:34
Forum: PHP Developer Forum