PHP Example HTML Javascript jQuery Ajax CSS Java MORE

PHP Switch Statement with example

The switch-case statement is an alternative to the if-elseif-else statement. It does the same thing as if-elseif-else statement.

How it Works

  • The switch expression is evaluated once.
  • The value of the expression is compared with the values of eachcCase.
  • If there is a match, the associated block of code is executed other wise the default block is executed.

Syntax

switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}

Example 1:

<!DOCTYPE html>
<html>
<body>
<?php
$favsport = "cricket";
switch ($favsport) {
case "hockey":
echo "Your favorite sport is Hocky!";
break;
case "cricket":
echo "Your favorite sport is Cricket!";
break;
case "football":
echo "Your favorite sport is Football!";
break;
case "badminton":
echo "Your favorite sport is Badminton!";
break;
default:
echo "Your favorite sport is neither Hockey, Tennis, nor Golf!";
}
?>
</body>
</html>

Run It Yourself »

Example 2:

<!DOCTYPE html>
<html>
<body>
<?php
$favsport = "cricket";
switch ($favsport) {
case "hockey":
echo "Your favorite sport is Hocky!";
break;
case "tennis":
echo "Your favorite sport is Cricket!";
break;
case "football":
echo "Your favorite sport is Football!";
break;
case "badminton":
echo "Your favorite sport is Badminton!";
break;
default:
echo "Your favorite sport is neither Hockey, Cricket, Football nor Golf!";
}
?>
</body>
</html>

Run It Yourself »

Example 3:

<!DOCTYPE html>
<html>
<body>
<?php
$d = date("D");
switch ($d){
case "Mon":
echo "Today is Monday";
break;
case "Tue":
echo "Today is Tuesday";
break;
case "Wed":
echo "Today is Wednesday";
break;
case "Thu":
echo "Today is Thursday";
break;
case "Fri":
echo "Today is Friday";
break;
case "Sat":
echo "Today is Saturday";
break;
case "Sun":
echo "Today is Sunday";
break;
default:
echo "Wonder which day is this ?";
}
?>
</body>
</html>

Run It Yourself »