简体   繁体   English

优化if-else条件

[英]Optimise a if-else condition

Suppose there are two arrays $a, $b . 假设有两个数组$a, $b At any given point at least one of them is not empty or both are not empty. 在任何给定的点上,至少有一个不为空或两者都不为空。

How do I optimise the following condition 如何优化以下条件

if(!$a)
{
  #TASK A
}
if(!b)
{
  #TASK B
}

if ($a['item']<$b['item'])
{
   #TASK A
}
else
{
  #TASK B
}

I don't want TASK A and B to be repeated twice in the program. 我不希望任务A和B在程序中重复两次。

if(!$a || ($b && ($a['item'] < $b['item']))){
// task A
}
else{
// task B
}
if(!$a || ($b && ($a['item'] < $b['item']))){
  // task A

}elseif(!$b || ($a && ($a['item'] >= $b['item']))){
  // task B
}

If the variables may not be set, use empty() or isset() 如果可能未设置变量,请使用empty()isset()

This will work, but it may not be optimal. 这将起作用,但可能不是最佳选择。 But the code is not really clear. 但是代码并不十分清楚。 Do TaskA and TaskB modify $a and $b? TaskA和TaskB是否修改$ a和$ b?

$aDone = false; 
$bDone = false;

if(!$a)
{
  #TASK A
  $aDone = true; 
}
if(!b)
{
  #TASK B
  $bDone = true;
}

if ($a['item'] < $b['item'])
{
   if (!$aDone)
   {
      #TASK A
   }
}
else 
{
   if (!$bDone)
   {
     #TASK B
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM