Switch multiple case statement

PhpSwitch Statement

Php Problem Overview


Can someone suggest me how can I replace the below code?

How do I rewrite the code in order to avoid the repetition of the block case 3:{code block A; break;}?

switch(i) {
  case 1:  {code block A; break;}

  case 2:  {code block b; break;}

  case 3:  {code block A; break;}

  default: {code block default; break;}
}

How can I have combined code for case 1 and case 3?

Php Solutions


Solution 1 - Php

This format is shown in the PHP docs:

switch (i) {
    case 1:
    case 3:
        code block A;
        break;
    case 2:
        code block B;
        break;
    default:
        code block default;
        break;
}

EDIT 04/19/2021:

With the release of PHP8 and the new match function, it is often a better solution to use match instead of switch.

For the example above, the equivalent with match would be :

$matchResult = match($i) {
    1, 3    => // code block A
    2       => // code block B
    default => // code block default
}

The match statement is shorter, doesn't require breaks and returns a value so you don't have to assign a value multiple times.

Moreover, match will act like it was doing a === instead of a ==. This will probably be subject to discussion but it is what it is.

Solution 2 - Php

Something like this

switch(i) {
	case 1:
	case 3:  {code block A; break;}

	case 2:  {code block b; break;}

	default: {code block default; break;}
}

Solution 3 - Php

Something like

    $i = 10;
    switch($i){
        case $i == 1 || $i > 3:
            echo "working";
            break;
        case 2:
            echo "i = 2";
            break;
        default: 
          echo "i = $i";
          break;
    }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionUnkown_BetterView Question on Stackoverflow
Solution 1 - PhpB FView Answer on Stackoverflow
Solution 2 - PhpmarciojcView Answer on Stackoverflow
Solution 3 - PhpHung PhamView Answer on Stackoverflow