shanks
shanks

Reputation: 2017

Optimise a if-else condition

Suppose there are two arrays $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.

Upvotes: 3

Views: 132

Answers (3)

Akinza
Akinza

Reputation: 157

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

Upvotes: 3

nice ass
nice ass

Reputation: 16709

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()

Upvotes: 1

GolezTrol
GolezTrol

Reputation: 116100

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

Upvotes: 0

Related Questions