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'
andcase '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..
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.
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.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With