Switch Statement
×
Home Courses Community Support
Switch Statement

Switch Statement is used when we have multiple conditions and don't want to use nested if else statement. Switch statement perform action based on the condition associated to that action. This statement eliminate the problem of long code of if else statement.
 

Let's code for assumption that Mr. Monu goes to Lord Shiv temple on Monday, Lord Hanuman temple on Tuesday, Lord Sai temple on Saturday and rest of the days he goes office directly.
 

<?php
$day = date("D");
switch ("$day"){
	case "Mon":
	echo "Mr. Monu will go to Lord Shiv temple first.";
	break;
	case ("Tue"):
	echo "Mr. Monu will go to Lord Hanuman temple first.";
	break;
	case ("Sat"):
	echo "Mr. Monu will go to Lord Shai temple first.";
	break;
	default:
	echo "Mr. Monu will go to office, not to temple.";
	}
?>

Output:

Output of this program depends on the date of your system. Copy paste this code in CodeLAB and check output.

 

If we don't use 'break' then it will print all the results leading the true conditions.

See below example-

<?php
$day = "Tue";
switch ("$day"){
	case "Mon":
	echo "Mr. Monu will go to Lord Shiv temple first.";
	case ("Tue"):
	echo "<br>Mr. Monu will go to Lord Hanuman temple first.";
	case ("Sat"):
	echo "<br>Mr. Monu will go to Lord Shai temple first.";
	default:
	echo "<br>Mr. Monu will go to office, not to temple.";
	}
?>

Output:

Mr. Monu will go to Lord Hanuman temple first.
Mr. Monu will go to Lord Shai temple first.
Mr. Monu will go to office, not to temple.

 

In the above code, we have removed break and set the $day value to 'Tue', so code print the condition which was ture and all other conditions next to true condition. 

 

 

← Preview

Nested If Else Statement

Next →

While Loop

NOTES

Our mission is to provide highly effective and quality education via innovative solutions. Geeksdemy look forward to bridge the gap between in-demand technology and academics in order to deliver innovative, easy, interesting and affordable learning across the Globe.

Courses

  • Python
  • Game Development with Unity 3D
  • Arduino
  • PCB & Circuit Designing
  • Robotics and Embedded C
  • 8051/8052 Embedded Systems
  • QuadCopter & UAV
  • MATLAB with Robotics
  • Raspberry Pi
Learn On the Go!
Get the Android App
Get the iOS App