PHP Switch Case Statement

In this tutorial, you will learn how to use the switch-case statement to evaluate an expression with different values in PHP.


PHP Switch Case Statement compares the same variable or expression with many values and executes the different blocks of codes depending on the condition match. This works the same as if-elseif-else condition in PHP.

PHP Switch Case Syntax

switch(expression){
case value1:
//code will execute if expression=valuee1
break;
case value2:
//code will execute if expression=valuee2
break;
......
default:
code to be executed if all cases are not matched;
}

How PHP Switch Case works

  • The expression is evaluated once and compared with each case value.
  • If a match is found, the corresponding statements are after the matching level executed. For example, if a match found with value2, then statements after case value2: are executed until a break is found.
  • If the break statement not found, then all the statements after the matching statements are executed.
  • It is not mandatory to use a default statement inside the PHP Switch case statement. If used, it must be the last statement.

PHP Switch Case Example

<?php
$num=11;
switch($num){
case 10:
echo("number is equals to 10");
break;
case 11:
echo("number is equal to 11");
break;
case 12:
echo("number is equal to 12");
break;
default:
echo("number is not equal to 10, 11 or 12");
}
?>

Output

number is equal to 11

Please get connected & share!

Advertisement