What is the difference between Switch and IF?

I know that this can be a simple question, but I want to know every opinion about this.

What is the difference between switch and IF function in PHP? What I see is that the "switch" function ever uses the "IF" function, which also applies there ... edit me if I'm wrong.

Or any performance difference between the two ??

+5
source share
4 answers

Or any performance difference between the two ??

Forget about the difference in performance at this level - it may be microscopic, but you will only feel it when doing hundreds of thousands of operations, if at all. switch- this is a design for better readability of the code and maintainability:

switch ($value) 
 {
 case 1:   .... break;
 case 2:   .... break;
 case 3:   .... break;
 case 4:   .... break;
 case 5:   .... break;
 default:  .... break;
 }

basically much cleaner and more readable than

if ($value == 1) { .... }
elseif ($value == 2) { .... }
elseif ($value == 3) { .... }
elseif ($value == 4) { .... }
elseif ($value == 5) { .... }
else { .... }

: Kuchen, - ( , ). , , 1000 . if .

  • if elseif ( ==) 174
  • if, elseif else ( ==) 223
  • if, elseif else ( ===) 130
  • switch/case 183
  • switch/case/default 215

( phpbench.com):

/case if/elseif . , === ( ) , == ().

+19

, , - - , .

, :

if($bla == 1) {

} elseif($bla == 2) {

} elseif($bla == 3) {

} etc...

:

switch($bla) {
  case 1:
    ...
    break;
  case 2:
    ...
    break;
  case 3:
    ...
    break;
  default:
    ...
    break;
}

, , if/else.

, - switch if/else.

+3

, .
.
, .

, 3-4 , , , , .

.

+2

Remember that the switch does not necessarily work as a simple if statement. Keeping in mind that the switch does not require a break at the end of each case, and leaving this gap, you can “fail” in the next case, it may also allow some interesting and somewhat complex “ifs”.

0
source

All Articles