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?
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.
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.
switch ($var) { case 'C': $c = 3; case 'B': $b = 2; case 'A': $a = 1; break; }
Should do what you want.
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.