PHP8 introduces the match expression, a feature that helps developers significantly simplify conditional logic. Compared to traditional switch or if-else statements, match expressions are more concise, readable, and can directly return values, making the code logic clearer.
In PHP7 and earlier versions, developers typically used switch statements or nested if-else statements for conditional logic. While functional, this approach often results in repetitive code, higher maintenance costs, and less intuitive logic.
The syntax of match expressions is similar to switch but functions as an expression and can return a value. Here’s an example demonstrating how to determine the type of a number:
function getType(int $number) { return match (true) { $number < 0 => 'negative', $number == 0 => 'zero', $number > 0 => 'positive', }; } echo getType(-5); // Output: negative echo getType(0); // Output: zero echo getType(10); // Output: positive
In this example, the getType function returns the type of the given number. Using true as the match condition allows handling multiple conditional branches easily.
Beyond number type checks, match expressions can handle more complex logic, such as returning prices based on product type:
function getPrice(string $productType) { return match ($productType) { 'book' => 20, 'clothes' => 50, 'electronics' => 100, default => 0, }; } echo getPrice('book'); // Output: 20 echo getPrice('clothes'); // Output: 50 echo getPrice('electronics'); // Output: 100 echo getPrice('unknown'); // Output: 0
Here, the getPrice function returns the price corresponding to different product types. If no condition matches, the default value 0 is returned.
Match expressions not only handle simple condition matching but also support combining conditions with logical operators and using anonymous functions to return results. These features make the code more flexible and suitable for complex business logic.
PHP8’s match expression provides an efficient and concise way to handle conditional logic, replacing verbose if-else or switch statements. Using match expressions improves code readability, reduces repetitive code, and boosts development efficiency. The examples in this article help developers quickly understand and apply match expressions in real projects.