Switch/Case vs If/Else (in PHP)

Although many programming languages use if/else and switch/case functions for conditional statements, but we’re discussing them here with regards to php specifically.

I’ve been asked several times by junior programmers that whats the difference between using switch-case and if-else functions in php.

Well, there are many differences. I’ll try to list them out and explain them here. If you’ve anything to add or correct, please let me know.

1. Switch/Case is Faster

Thats right. Switch case is almost 25% faster than If/Else statements. On a small scale or single logic, this difference might seem very negligible, but on repetitive and very high traffic code, switch is definitely a plus.

2. Switch/Case is easier to read

Self explanatory.

Just read through the following if/else code and then the switch/case code for the same logic and see which one is easier to read and modify/edit.

If/Else:

if($a=1){ 
  // do this 
}elseif($a=2){
  // do this 
}elseif($a=3){
  // do this 
}elseif($a=4){
  // do this 
}elseif($a=5){
  // do this 
}elseif($a=6){
  // do this 
}else{
  //do this
}

Switch/Case:

switch($a){

  case 1: 
           //do this
           break;

  case 2: 
           //do this
           break;

  case 3: 
           //do this
           break;

  case 4: 
           //do this
           break;

  case 5: 
           //do this
           break;

  case 6: 
           //do this
           break;
  default:
           //do this
}

3. Some other difference

If/Else and Switch/Case aren’t identical functions. They might give similar output in most cases which we deploy them in, but they do work differently in various conditions.

E.g: if we don’t use “break;” at the end of each case in switch function. It will look for the case which is true and then output all the cases below it (if none had break in it). Which means, if in above example we didn’t have break; in it and the case 4 turned out to be true, it will run and execute + output the code from case 4, 5 and so on.

This is surely beneficial in some situations, but not good in others.

hire best wordpress php css developer
Need Help? Hire me now!
I can help you in anything related to webdevelopment, including: HTML, CSS, PHP & MySql, WordPress (plugins & themes development, others), regular expressions, server management, etc.

Leave a Reply

Your email address will not be published.