July 26, 2017

Core PHP: The Switch Statement (5.11)

The switch Statement


The switch statement is an alternative to the if-elseif-else statement.
Use the switch statement to select one of a number of blocks of code to be executed.

Syntax:
switch (n) {
  case value1:
    //code to be executed if n=value1
    break;
  case value2:
     //code to be executed if n=value2
     break;
  ...
  default:
    // code to be executed if n is different from all labels
}

First, our single expression, n (most often a variable), is evaluated once. Next, the value of the expression is compared with the value of each case in the structure. If there is a match, the block of code associated with that case is executed.

Using nested if else statements results in similar behavior, but switch offers a more elegant and optimal solution.

No comments:

Post a Comment