Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Executing multiple case using PHP switch statement

I have to execute multiple set of instructions based upon a value, for example.

$value = 'AA';
switch ($value) {
    case 'AA':
        echo "value equals  1";
    continue;
    case 'BB':
        echo "value equals 2";
    continue;
    case 'CC' || 'AA':
        echo "value equals 3";
    break;
}

What i am expecting from the above code is it should execute multiple cases based upon the values passed, the variable $value contains AA as the value so hence i am expecting it to execute both

case 'AA' and
case 'CC' || 'AA'

so it should print out value equals 1 value equals 3 however it does not execute it that way i am getting only value equals 1 as output. and if i remove continue from the statement it executes all three cases which is logically wrong. does the PHP's switch statement support multiple cases to be executed based on a single value? is there any workaround for this?

thank you..

like image 746
Ibrahim Azhar Armar Avatar asked Aug 19 '11 05:08

Ibrahim Azhar Armar


People also ask

Can you have multiple cases in a switch statement?

As per the above syntax, switch statement contains an expression or literal value. An expression will return a value when evaluated. The switch can includes multiple cases where each case represents a particular value.

Does switch statement execute all cases?

The body of a switch statement is known as a switch block. A statement in the switch block can be labeled with one or more case or default labels. The switch statement evaluates its expression, then executes all statements that follow the matching case label.

How many cases can switch statement have?

Microsoft C doesn't limit the number of case values in a switch statement. The number is limited only by the available memory. ANSI C requires at least 257 case labels be allowed in a switch statement.


1 Answers

When a break is missing then a switch statement enables falling through to the next condition:

$value = 'AA';
switch ($value) {
    case 'AA':
        echo "value equals  1"; // this case has no break, enables fallthrough
    case 'CC':
        echo "value equals 3"; // this one executes for both AA and CC
    break;
    case 'BB':
        echo "value equals 2";
    break;
}
like image 200
Saul Avatar answered Oct 28 '22 17:10

Saul