PHP 8's match expression replaces switch statements with cleaner syntax that eliminates the need for break statements and prevents accidental fall-through bugs. Match is more concise and safer, making it the better choice for most conditional logic.
Chapters
Switch statements have been around since the start of php. Pass in a variable to the switch statement and then its value is caught on one or many of the related case statements. In this example, if numpost is 0, the first case 0 statement is matched and then the message is assigned to there are no posts. Break then tells the switch statement that it's all done and to exit the switch. You can also have a conditional block process depending on multiple values. For example, the 1, 2, 3 will be caught on this single case conditional block switch is still heavily used, but it's pretty verbose and if you forget one of these break keywords you might be in trouble. Match was introduced in PHP8 and aims to greatly simplify switch statements. This code block actually contains the exact same logic as the previous switch statement, but it's much more simpler and easier to reason about. Note that it doesn't need any case statements, it doesn't need a break keyword, it just works pretty much as you expect. This really helps streamline your code and helps prevent any bugs or errors from making their way into your PHP Apple.