Incorporating match Expressions
Understand how to use match expressions introduced in PHP 8 to replace switch statements. Learn their syntax, differences, and practical implementation to write cleaner and more accurate code, including examples involving currency symbols and CAPTCHA distortion strategies.
We'll cover the following...
Among the many incredibly useful features introduced in PHP 8, match expressions definitely stand out. match expressions are a more accurate shorthand syntax that can potentially replace the tired old switch statement from the C language. In this lesson, we will learn how to produce cleaner and more accurate program code by replacing switch statements with match expressions.
match expression general syntax
match expression syntax is much like that of an array, where the key is the item to match and the value is an expression. Here is the general syntax for match:
$result = match(<EXPRESSION>) {<ITEM> => <EXPRESSION>,[<ITEM> => <EXPRESSION>,]default => <DEFAULT EXPRESSION>};
The expression must be a valid PHP expression. Examples of ...