Start · Sprachen · PHP · Referenz · match

match

Anweisung

Moderner Multi-Way-Branch — als Ausdruck, mit strict comparison, ohne Fall-Through.

seit PHP 8.0.0 Kategorie: control-flow

Signatur

$result = match ($value) { A, B => x, C => y, default => z, };

Beschreibung

Der bessere switch. Ohne default-Zweig wirft es UnhandledMatchError bei ungematchtem Wert — was oft ein Feature ist, kein Bug.

Rückgabewert

Typ
mixed
Beschreibung
Wert des matchenden Arms.

Beispiele

Basis

<?php

$level = match ($role) {
    'admin', 'moderator' => 10,
    'user'               => 1,
    default              => 0,
};

Mit throw

<?php

$factor = match ($currency) {
    'EUR', 'USD' => 1,
    'CHF'        => 1.05,
    default      => throw new InvalidArgumentException("Unbekannt: $currency"),
};