The switch block allows a program to choose what code to execute based on the value of a variable. This is helpful in handling multi-case scenarios where you are unsure about what the variable's value will be at the time of execution. It also servers as a more organized alternative to multiple "if else" statements.
The following example deals with code that executes based on the numeric value of variable $x
switch ($x)
{case 4:
$x=$x+2
break;
case 5:
$x=$x+4 break;
case 6:
$x=$x+10
break;
default:
$x=7;
}
default:
$x=7;
}
The code above determines what value to add to $x, based on what value it holds going into the switch statement. For example, 2 is added to $x if $x=4 at the time of execution. If $x is not equal to 4, 5, or 6 at the time of execution, then the "default" code is executed, setting $x=7.
While it would be possible to execute the same code with a handful of "if and else" statements, most would agree that the switch option provides for a cleaner code.
No comments:
Post a Comment