Optimize if-else condition

Let's say there are two arrays $a, $b

. At any given moment, at least one of them is not empty, or both are not empty.

How do I optimize 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 PROBLEM A and B to be repeated twice in the program.

+3


source to share


3 answers


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

      



+3


source


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

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

      



If the variables cannot be set use empty()

orisset()

+1


source


This will work, but it may not be optimal. But the code is not entirely clear. Do TaskA and TaskB do $ a and $ 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
   }
}

      

0


source







All Articles