Menu

Need MCA Or B.tech College Project Contact Us: +91 9437911966 (Whatsapp) Students Tutorial


PHP Switch Statement with example

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>

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>

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>