Switch statement

Updated: 09/12/2023 by Computer Hope
switch statement

In programming, the switch statement is a conditional block used to shorten a long set of if else statements. For example, consider the below if else blocks (using PHP (PHP: Hypertext Preprocessor)) in the example below.

if ($num == 0) {
 echo "The number is zero!";
elseif ($num == 1) {
 echo "The number is one!";
elseif ($num == 2) {
 echo "The number is two!";
else {
 echo "Error!";

Rather than writing several if else blocks to run statements based on the value of one variable, you can use the switch statement to perform the task with fewer blocks of code. Let's take a look at the following code example.

switch ($num) {
 case 0 : echo "The number is zero!"; break;
 case 1 : echo "The number is one!"; break;
 case 2 : echo "The number is two!"; break;
 default : echo "Error!";

With the switch statement, the variable name is used once in the opening line. A case keyword is used to provide the possible values of the variable. That keyword is followed by a colon and a set of statements to run if the variable equals a corresponding value. The keyword default is used to handle any values not covered with one of the cases (like an ending else statement).

Programming terms, Switch