Jason
Jason

Reputation: 49

How can I simplfy this logic

I'm having trouble simplifying this conditional statements logic. Is there a more effervescent way of writing this?

if(($x || $a) && ($x || $y))
{
   if($x){
          return true;
   }
}
return false;

Upvotes: 3

Views: 197

Answers (8)

Gumbo
Gumbo

Reputation: 655755

The condition of the outer if, ($x || $a) && ($x || $y), is equivalent to $x || ($a && $y). When we conjunct that with the condition that $x must also be true (inner if), we get ($x || ($a && $y)) && $x. And that is equivalent to $x && $x || $x && $a && $y which can be reduced to $x || $x && $a && $y. In both OR branches $x must be true to proceed. But if the $x in the right branch is true, the whole condition is already true.

So the only variable that needs to be true is $x:

return (bool) $x;

Upvotes: 2

animuson
animuson

Reputation: 54787

if ($x) return true;
return false;

According to your statement, you only return true if $x is true, therefore that is the only statement you really need to check for, correct? The variables $a and $y are completely irrelevant.

Edit: Same thing as:

return (bool) $x;

Upvotes: 6

Carl Smotricz
Carl Smotricz

Reputation: 67820

If you only return true if $x is true, then the rest of the code is irrelevant. Thus,

return (bool) $x;

EDIT: Oops... bool is a cast, not a function.

Upvotes: 4

matt
matt

Reputation: 4244

   if($x){
          return true;
   }

   return false;

?

Edit:

return $x

Upvotes: 0

Kjetil Watnedal
Kjetil Watnedal

Reputation: 6167

Like several people have already said, only $x matters in your code. I guess the shortest possible code is:

return $x

Upvotes: 1

Chris Moutray
Chris Moutray

Reputation: 18399

You could write this as a one line expression...

return $x;

regardless of $a and $y, $x has to be true to return true

Upvotes: 0

fastcodejava
fastcodejava

Reputation: 41117

if(($x && $a && $y)
{
    return true;
}
return false;

EDIT : it is simply return $x;

Upvotes: 0

Pratik Deoghare
Pratik Deoghare

Reputation: 37212

if($x && ($a || $y))
     return true;

return false;

Upvotes: 0

Related Questions