switch statement in PHP

In PHP switch statement is used to perform different actions based on different conditions. It works like if...elseif...else statement.

Syntax :
switch(n){
      case label_1:
            Code to be executed if n=label_1;
            break;
      case label_2:
            Code to be executed if n=label_2;
            break;
      ...............
      default:
            Code to be executed if n is different from all labels;
}

Example :
<?php
$lang = "php";
switch($lang)
{
      case "php":
            echo "Language is php";
            break;
      case "python":
            echo "Language is python";
            break;
      case "java":
            echo "Language is java";
            break;
      default:
            echo "No Language selected";
            break;
}
?>

Output :
Language is php

The switch statement differs from the if...elseif...else statement in one important way. The switch statement executes line by line (i.e. statement by statement) and once PHP finds a case statement that evaluates to true, it's not only executes the code corresponding to that case statement, but also executes all the subsequent case statements till the end of the switch block automatically. To prevent this add a break statement to the end of each case block. The break statement tells PHP to break out of the switch-case statement block once it executes the code associated with the first true case.

0 Comments