views:

119

answers:

8

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;
+6  A: 
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;
animuson
He might want to do that if and only if one of `$a`, `$y` is `true`.
TheMachineCharmer
I would use `return (bool) $x;`
Gumbo
animuson
Why not write `return $x;`?
fastcodejava
@Gumbo: That would be good. :) @fastcodejava: No one said `$x` was a boolean.
animuson
A: 
   if($x){
          return true;
   }

   return false;

?

Edit:

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

return false;
TheMachineCharmer
Gumbo
A: 
if(($x && $a && $y)
{
    return true;
}
return false;

EDIT : it is simply return $x;

fastcodejava
+3  A: 

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.

Carl Smotricz
A: 

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

return $x;

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

mouters
+1  A: 

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

return $x
Kjetil Watnedal
What if `$x` is a string or a number? Then it does not return a boolean true/false.
animuson
You are right. Seems like we do need the if($x) return true; else return false, then. Anyway, why have a method for this at all when the only thing it does is to check the value of $x...
Kjetil Watnedal
I don't know, it seems like it would be a good school assignment, who knows.
animuson
+1  A: 

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;
Gumbo