3

Let's say I have a switch statement like this:

switch ($var)
{
    case 'A':
       $a = 1;
       break;

    case 'B':
       $a = 1;
       $b = 2;
       break;

    case 'C':
       $a = 1;
       $b = 2;
       $c = 3;
       break;
}

Is there a way that I can structure that switch statement to have the repeated $a = 1 and $b = 2 appear like once?

4 Answers 4

9

Just revert your order of case statements and remove the break statements.

switch ($var)
{
    case 'C':
       $c = 3;
    case 'B':
       $b = 2;
    case 'A':
       $a = 1;
       break;
}

From the manual:

It is important to understand how the switch statement is executed in order to avoid mistakes. The switch statement executes line by line (actually, statement by statement). In the beginning, no code is executed. Only when a case statement is found with a value that matches the value of the switch expression does PHP begin to execute the statements. PHP continues to execute the statements until the end of the switch block, or the first time it sees a break statement. If you don't write a break statement at the end of a case's statement list, PHP will go on executing the statements of the following case.

Sign up to request clarification or add additional context in comments.

Comments

6

Like this:

switch($var) {
    case 'C':
        $c = 3;
        // fallthrough
    case 'B':
        $b = 2;
        // fallthrough
    case 'A':
        $a = 1;
}

The comments are of course optional, but I like to leave them there to ensure I don't forget that the lack of a break is deliberate.

1 Comment

I also started to put them in once I found them in some other code. They are really useful comments. "fallthrough intended" or something similar. +1 so.
2
switch ($var) {
  case 'C':
    $c = 3;
  case 'B':
    $b = 2;
  case 'A':
    $a = 1;
    break;
}

Should do what you want.

Comments

2
switch($var) {
    case 'C':
        $c = 3;
    case 'B':
        $b = 2;
    case 'A':
        $a = 1;
}

By not using breaks, if $var for example contains 'C' the whole switch structure will get executed. If $var is 'B' the switch will enter at case 'B' and execute from there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.