Executing multiple case using PHP 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;
}
The switch
statement needs literals in the case blocks. Use an if
statements instead.
You can use other sorts of loop to iterate
through the value, and then use IF
's for comparison. Doing comparison/condition checking isn't possible in the switch
cases.
One way to accomplish what you want to do is like this (note IF is being used):
$value = 'AA';
switch($value)
{
case ('AA'):
echo "value equals 1<br />";
case ('BB'):
if ($value == 'BB'){
echo "value equals 2<br />";
}
case (('AA') || ('CC')):
echo "value equals 3<br />";
break;
}
Outputs:
value equals 1
value equals 3
NOTE:- the above solution isn't right although its outputting what you need its not the right solution and if possible i would recommend avoiding. Your needs can easily be fixed using non-switch/case alternatives.