EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login

PHP Switch Statement

Home » Software Development » Software Development Tutorials » PHP Tutorial » PHP Switch Statement

php Switch Statement

Introduction to PHP Switch Statement

If we talk in generic coding terminologies then being a novice to coding, you would have seen “if” statement to handle condition checks and do some action on their validations, now lets take a case that you are writing logic for traffic light systems design and if you look to proceed with standard if conditions then probably you would end up with one “if”, one “else if or if” and one “else” statement, and if any other synonymous kind of business logic appears where such criterions are high in number and they belong to the same category, then code won’t appear good and for that we have “switch” statement, where you just need to write this statement once only and describe certain cases associated under a common category and business logic to be implemented in association with that.

Detailed Description of PHP Switch Statement

Let’s see a PHP snippet where we are having a range of age and a corresponding message is being displayed to represent category of those people.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

$age = ’7-12’
switch($age)
{
case '0-1': echo 'it's a baby';
break;
case '2-3' : echo 'toddler';
break;
case '4-6' : echo 'infant';
break;
case '7-12': echo 'child';
break;
default : echo ‘others’;
}

  • So you may have got a rough idea after seeing the example displayed above, the example carries the implementation of such a condition using just one ‘switch’ statement rather than putting ourselves into multiple if and else statements.
  • The Switch takes common criterion parameter as input, which is going to take a set of values upon which we need to apply the conditional evaluation for business logic implementation.
  • As in the above case, the age variable shows that the age range mentioned matches ‘7-12’, so we will get ‘child’ in the output.
  • Let’s now see the order of processing and how much time will be elapsed in the traversal of control. As the age variable is provided as input, the case expression values are evaluated against the test value, the first case is checked, then the condition is not met, control flows to next statement performs synonymous kind of evaluation and keeps on hunting till it gets its relevant expression.
  • Now once it gets its test value evaluated, the echo ‘child’ statement gets executed and then?
  • Will the control flow to default also? As it seems something like a condition that will get executed by default. Well, it is not so. You must see that in every case statement block there is a ‘break’ statement too, the task of ‘break’ is to take the flow out of switch context and proceed with the next logical instruction in the program file.
  • Default statement gets executed only in case if none of the conditions mentioned above are met, like if I mention the age to be 24 years, then the output will appear to be ‘others’.
  • Hence it’s logical to place the default statement at the end of the file.
  • This order of placement matters a lot while you write code, and you should be well aware of the kind of input data that you will be getting mostly as test condition, its better to keep that case at the top, so that maximum users get the result as early possible with first line only. This could be done after analysis of data in the system you are deploying.
  • Pay a little thought on fact, why there is no break in the default statement, the above description carries the answer although.

Syntax 

switch (testvalue) {
case label1:
code to be executed if testvalue = label1;
break;
case label2:
code to be executed if testvalue = label2;
break;
case label3:
code to be executed if testvalue = label3;
break;
default:
code to be executed if testvalue is different from above;
}

We have already shared a program in the above section on this logic only, refer to that for better understanding with a use case.

Flow Chart for Switch

The flow chart for PHP switch is the same as other coding languages’ switch statements as this is common functionality in every language.

Popular Course in this category
PHP Training (5 Courses, 3 Project)5 Online Courses | 3 Hands-on Project | 28+ Hours | Verifiable Certificate of Completion | Lifetime Access
4.5 (5,726 ratings)
Course Price

View Course

Related Courses
Java Servlet Training (6 Courses, 12 Projects)All in One Software Development Bundle (600+ Courses, 50+ projects)

Flow Chart for Switch

Examples

Kindly refer to the example shared in the details section, that carries detailed information about working and let’s take here some application use cases for better clarity of the picture.

Use Case 1 

Let’s say you are gathering the data related to students who have birthday’s in each of the respective month of calendar year, here you can put month into switch criteria and can have 12 different arrays to store data of students pertaining to different months, hence keep on adding data to each of the array as the condition is met and for a count of 5000 students in a school, likely your all arrays will get occupied.

Use Case 2 

Let’s talk about small scale design of a calculator where you need to perform addition, subtraction and multiplication like operations, in a switch, you can take name of operation, validate it against case labels and once met, the business logic there would return the value of output based on respective calculations.

Conclusion

We saw the cases where the increase in a number of conditions against a category if gets increased then it’s better to adapt with a switch statement, it makes code more clear, readable and can make it fast too based on data analysis and placement of logics accordingly. We saw syntax for implementation in PHP, for example, and few relevant use cases.

Recommended Articles

This is a guide to PHP Switch Statement. Here we discuss the detailed description of PHP switch statements, flow chart for a switch. You can also go through our other suggested articles –

  1. Overriding in PHP
  2. PHP Frameworks
  3. PHP Math Functions
  4. PHP Constants

PHP Training (5 Courses, 3 Project)

5 Online Courses

3 Hands-on Project

28+ Hours

Verifiable Certificate of Completion

Lifetime Access

Learn More

0 Shares
Share
Tweet
Share
Primary Sidebar
PHP Tutorial
  • Control Statements
    • Control Statement in PHP
    • PHP if Statement
    • if else Statement in PHP
    • elseif in PHP
    • PHP Switch Statement
    • Continue in PHP
    • Break in PHP
  • PHP Basic
    • Introduction To PHP
    • What is PHP
    • PHP Keywords
    • Advantages of PHP
    • Career In PHP
    • Comments in PHP
    • PHP Commands
    • PHP Frameworks
    • PHP Compiler
    • Variables in PHP
    • PHP Superglobal Variables
    • PHP Versions
    • Object in PHP
    • What is Drupal
    • Top PHP Frameworks
    • WebStorm IDE
    • What is phpMyAdmin?
    • PhpStorm
    • Install phpMyAdmin
    • Phalcon Model
  • Data Types
    • PHP Data Types
    • PHP Integer
    • PHP Booleans
  • Operators
    • PHP Operators
    • Arithmetic Operators in PHP
    • Comparison Operators in PHP
    • Logical Operators in PHP
    • Bitwise Operators in PHP
    • Ternary Operator in PHP
    • PHP String Operators
  • Loops
    • PHP Loops
    • For Loop in PHP
    • PHP Do While Loop
    • PHP While Loop
    • While Loop in PHP
    • Foreach Loop in PHP
  • Constructor
    • Constructor in PHP
    • Destructor in PHP
  • State Management
    • Cookie in PHP
    • Sessions in PHP
  • Array
    • What is PHP Array
    • Arrays in PHP
    • 2D Arrays in PHP
    • Associative Array in PHP 
    • Multidimensional Array in PHP
    • Indexed Array in PHP
    • PHP Array Functions
    • PHP unset Array
    • PHP Append Array
    • PHP Array Search
    • PHP Split Array
    • PHP array_push()
    • PHP array_pop()
  • Functions
    • Functions in PHP
    • PHP Math Functions
    • PHP Recursive Function
    • PHP String Functions
    • Hashing Function in PHP
    • Date Function in PHP
    • PHP Anonymous Function
    • Calendar in PHP
    • PHP Call Function
    • PHP Pass by Reference
    • PHP ucfirst()
    • PHP ucwords()
    • trim() in PHP
    • isset() Function in PHP
    • PHP replace
    • PHP fpm
    • PHP strpos
    • preg_match in PHP
    • PHP preg_replace()
    • PHP ob_start()
    • PHP Reflection
    • PHP Split String
    • PHP URL
    • PHP preg_match_all
    • PHP strtoupper()
    • PHP preg_split()
    • PHP substr_replace()
    • PHP setlocale()
    • PHP substr_count()
    • PHP Serialize
    • PHP strlen()
    • PHP async
    • PHP Date Time Functions
    • PHP timezone
    • PHP Data Object
    • print_r() in PHP
    • PHP header()
    • PHP strip_tags()
    • PHP chop()
    • PHP MD5()
    • PHP unset()
    • PHP crypt()
    • PHP wordwrap()
    • PHP is_null()
    • PHP strtok()
    • PHP bin2hex()
    • PHP parse_str()
    • PHP levenshtein()
    • PHP addslashes()
    • PHP strtotime
    • PHP sha1()
    • PHP explode()
    • PHP sscanf()
    • PHP require_once
    • PHP Zip Files
    • PHP $_SERVER
    • PHP $_POST
    • PHP Include and Require
    • PHP POST Method
  • Advanced
    • Overloading in PHP
    • Overriding in PHP
    • Method Overloading in PHP
    • Inheritance in PHP
    • Multiple Inheritance in PHP
    • PHP Interface
    • Encapsulation in PHP
    • PHP Constants
    • PHP Magic Constants
    • PHP Regular Expressions
    • PHP GET Method
    • PHP Annotations
    • PHP Encryption
    • PHP file Functions
    • PHP readfile
    • PHP?Write File
    • PHP Append File
    • PHP Type Hinting
    • PHP Filters
    • PHP Float
    • PHP Form
    • PHP Form Validation
    • Sorting in PHP
    • PHP usort()
    • PHP Stack Trace
    • PHP Stack Overflow
    • PHP Pagination
    • PHP implode
    • Polymorphism in PHP
    • Abstract Class in PHP
    • PHP Final Class
    • PHP Custom Exception
    • error_reporting() in PHP
    • PHP Log Errors
    • Access Modifiers in PHP
    • PHP Change Date Format
    • Static Method in PHP
    • PHP File Handling
    • PHP Output Buffering
    • Get IP Address in PHP
    • Upload a File in PHP
    • String in PHP
    • Public Function in PHP
    • Private in PHP
    • Protected in PHP
    • basename in PHP
    • Validation in PHP
    • PHP mail()
    • PHP Email Form
    • PHP Directory
    • PHP Create Session
    • PHP include_once
    • PHP json_decode
    • PHP XMLWriter
    • PHP XML Reader
    • PHP XML Parser
    • PHP XML into Array
    • Phalcon Framework
  • Programs
    • Patterns in PHP
    • Star Patterns in PHP
    • Swapping in PHP
    • Fibonacci Series PHP
    • Factorial in PHP
    • Reverse String in PHP
    • Square Root in PHP
    • Random Number Generator in PHP
    • Palindrome in PHP
    • Prime Numbers in PHP
    • Armstrong Number in PHP
    • Socket Programming in PHP
    • Login Page in PHP
    • PHP Login Template
    • PHP Object to String
  • Database
    • PHP Database Connection
    • How to Connect Database to PHP
  • Interview Questions
    • PHP Interview Questions
    • PHP OOP Interview Questions
    • CakePHP Interview Questions
    • Core PHP Interview Questions

Related Courses

PHP Training Course

Java Servlet Training

Software Development Course Training

Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

© 2020 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you
Book Your One Instructor : One Learner Free Class

Let’s Get Started

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you
EDUCBA Login

Forgot Password?

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

Special Offer - PHP Training (5 Courses, 3 Project) Learn More