如何优化多条件、相同输出的中频条件

时间:2021-08-11 作者:Sahasrar

我的目的是编写可持续且易于阅读的代码。性能也很重要,因为这应该是应用程序的核心,所以它将通过数百次。您对优化这段长代码有什么建议吗?我的第一个想法是将其编写为数组并检查数组是否包含。

      if(string == "apple"){
        Detail = false;
        bShowNew = true;        
      }
      if(string == "banana"){
        Detail = false;
        bShowNew = true;       
      }
      if(string == "kiwi"){
        Detail = false;
        bShowNew = true;          
      }
      if(string == "lemon"){
        Detail = false;
        bShowNew = true;          
      }
      if(string == "lime"){
        Detail = false;
        bShowNew = true;          
      }
      if(string == "mango"){
        Detail = false;
        bShowNew = true;         
      }
      if(string == "orange"){
        Detail = false;
        bShowNew = true;        
      }
      if(string == "pear"){
        Detail = false;
        bShowNew = true;           
      }
      if(string == "pineapple"){
        Detail = false;
        bShowNew = true;            
      }
      if(string == "plum"){
        Detail = false;
        bShowNew = true;          
      }
      if(string == "greenapple"){
        Detail = false;
        bShowNew = true;    
      }
      if(string == "redapple"){
        Detail = false;
        bShowNew = true;          
      }
      if(string == "blueapple"){
        Detail = false;
        bShowNew = true;        
      }
      if(string == "grenkiwi"){
        Detail = false;
        bShowNew = true;           
      }
      if(string == "brownkiwi"){
        Detail = false;
        bShowNew = true;           
      }
      if(string == "yellowmango"){
        Detail = false;
        bShowNew = true;         
      }
      if(string == "redmango"){
        Detail = false;
        bShowNew = true;           
      }
      if(string == "greenmango"){
        Detail = false;
        bShowNew = true;           
      }
      if(string == "purpleplum"){
        Detail = false;
        bShowNew = true;           
      }
    }

1 个回复
SO网友:Buttered_Toast

当然

你可以使用in_array 对于这种类型的支票,类似这样的

if (in_array($string, [\'apple\', \'banana\', \'kiwi\'])) { // keep adding as many as you need
    $Detail = false;
    $bShowNew = true;
}
如果数组变大,可以创建一个包含该数组的变量

$allowed = [
    \'apple\',
    \'banana\',
    \'kiwi\'
    // etc... 
];

if (in_array($string, $allowed)) { // keep adding as many as you need
    $Detail = false;
    $bShowNew = true;
}
这将完全相同,但更干净,更容易阅读