Switch vs if statements

后端 未结 6 1063
無奈伤痛
無奈伤痛 2020-12-17 10:15

I\'m in a dilemma. Which is best to use and why.. switch or if?

switch ($x) 
{
case 1:
  //mysql query 
  //echo something
  break;
case 2:
  //mysql query 
         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-12-17 10:47

    First what you have is not the same

    switch(value)
      case condition1:
        break;
      case condition2:
        break
    
    if (condition1) {
    }
    if (condition2) {
    }
    

    These are synonymous

    switch(value)
      case condition1:
        break;
      case condition2:
        break
    
    if (condition1) {
    }
    else if (condition2) {
    }
    

    Second if you are talking about my second example where the two are synonymous. Then using switch statements can ease some pain in coding lots of if ..else if statements....

    Switches in my point of view can also provide a bit more readability. But even then there are times when using if...else is simply better especially with complex logic.

提交回复
热议问题