PHP Switch..Case

  • Hi guys, in this tutorial we will learn PHP Switch Statement.
  • Switch cases are control structures that allow you to execute code segments based on the given conditions. This creates dynamic PHP behavior.
  • PHP provides a switch statement that allows you to conditionally execute the code block. The PHP switch statement compares an expression against a variable or many different values and executes a code block based on its same value.

PHP Syntax

<?php
	switch(n){
  case label1:
    //===========
    //label1 Code
    //===========
    break;
  case label2:
    //===========
    //label2 Code
    //===========
    break;
  case label3:
    //===========
    //label3 Code
    //===========
    break;
    ...
  default:
    //===========
    //default Code
    //===========
}
?>

PHP Example

Edit it yourself

<!DOCTYPE html>
<html>
<body>

<?php
  $theme = 2;

switch ($favcolor) {
  case 1:
    echo "Theme 1 is a selected";
    break;
  case 2:
    echo "Theme 2 is a selected";
    break;
  case 3:
    echo "Theme 3 is a selected";
    break;
  default:
    echo " Default theme selected!";
}
?>


</body>
</html>

Output of PHP comment

Edit it yourself

Theme 2 is a selected

  • Previous
  • Next