Switch statement

Updated: 08/08/2017 by Computer Hope

switch statementIn programming, the switch statement is a conditional block used as a method of shortening a long set of if else statements. For example, consider the below if else blocks (using PHP), 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, which is followed by a colon and a set of statements to run if the variable is equal to a corresponding value. The keyword default is used to handle any values that are not covered with one of the cases (like an ending else statement).

Programming terms