My blog

posts

Embrace match() Statements for Simplicity!

Images are great sometimes.


The comparison of the classic if/else if/else statements and the switch statement to the new match expression introduced in PHP 8.0.

Here is a brief explanation of each:

Classic IF statements

These statements use the ifelseif, and else keywords to check for different conditions and execute the corresponding code. For example:

if ($task-succeeded()) {
  return $this->addSucceededTask($task);
} elseif ($task-wasSkipped()) {
  return $this->addSkippedTask($task);
} else {
  return $this->addFailedTask($task);
}

Switch statements

Switch statements use the switch and case keywords to check for a single condition and execute the corresponding code. For example:

switch (true) {
  case $task-succeeded():
    return $this->addSucceededTask($task);
  case $task-wasSkipped():
    return $this->addSkippedTask($task);
  default:
    return $this->addFailedTask($task);
}

Match expressions

Match expressions are a new way to check for different conditions and execute the corresponding code. They are more concise and easier to read than classic if/else if/else statements and switch statements. For example:

return match (true) {
  $task-succeeded() => $this->addSucceededTask($task),
  $task-wasSkipped() => $this->addSkippedTask($task),
  default => $this->addFailedTask($task),
};

Advantages of match expressions:

  • Match expressions are more concise and easier to read than classic if/else if/else statements and switch statements.
  • Match expressions are more expressive and can be used to match complex expressions.
  • Match expressions are exhaustive, which means that they must handle all possible cases. This helps to prevent errors.

Overall, match expressions are a more modern and efficient way to check for different conditions and execute the corresponding code.

Which one should you use?

If you are writing new code, I recommend using match expressions. They are more concise, expressive, and exhaustive than classic if/else if/else statements and switch statements.

If you are working on existing code, you can gradually migrate to match expressions as you have the opportunity.


/

222 Laravel , PHP January 2, 2024 1 comments

1 Comments

  • Indeed a great observation of the operators.

    Reply

Add a comment