PHP Switch Statement

Switch Statement is a variant of the if-else combination and is used when we need to compare a variable against a large number of values depending on the value that is matched.

Syntax

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

In case of if...elseif...else statement same variable is compared again and again with different values. This looks quite cumbersome, specially when later want to change the expression used in all of the tests. For this purpose, PHP provides an easy way to run these types of tests: the switch statement.

Example

<?php 
$stdcode = "001";
switch ($stdcode) {
    case "001":
        echo "std code pertains to New Delhi!";
        break;
    case "002":
        echo "std code pertains to Mumbai!";
        break;
    case "003":
        echo "std code pertains to Kolkata!";
        break;
    case "004":
        echo "std code pertains to Chennai!";
        break;	
    default:
        echo "std code does not pertain to any Metro!";
}

This will produce following result:

std code pertains to New Delhi!


 
SHARE THIS IF YOU LIKE!
submit to reddit

SUBSCRIBE FOR LATEST UPDATES
HAVE WE CONNECTED ON FACEBOOK?
TOP TUTORIALSTOP CODE EXAMPLESTOP LIVE DEMOLINKSSTAY CONNECTED
HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
PHP Tutorial
Developer Tools
Javascript
AngularJS
Google MAP API V3
ASP.NET
Javascript
AngularJS
Google MAP API V3
Contact Us
Advertise with Us
Privacy Policy
Disclaimer
Stay connected. We actually like you. If you want to get up to the minute updates, then connect with us on your fav below.
 
Twitter   Linkedin   Facebook   Google+    RSS   Pinterest
 
Protected by Copyscape Original Content Checker
 
 
Copyright ©2017 www.techstrikers.com Unauthorized reproduction/replication of any part of this site is prohibited.