What is the difference between Switch and IF?

前端 未结 5 546
终归单人心
终归单人心 2021-01-13 10:30

I know this may be simple question but want to know every ones opinion on this.

what is the difference between switch and IF function in PHP?? What I can see is wher

5条回答
  •  攒了一身酷
    2021-01-13 10:43

    If you have simple conditions, like if something equates to something else, then a switch is ideal.

    For example, instead of doing the following:

    if($bla == 1) {
    
    } elseif($bla == 2) {
    
    } elseif($bla == 3) {
    
    } etc...
    

    It's better to do it like this:

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

    Alternatively, if you have complex conditions, you should use an if/else.

    I think that this is all a matter of opinion though - some people just don't use switch statements at all, and stick with if/else.

提交回复
热议问题