Search code examples
phpif-statementlogical-operatorscomparison-operators

Long logical operator comparisons


I have three variables which determine an outcome. There is only two outcomes but the outcome is based on the variables. I have thought up some long if statements but I am wondering if there is a cleaner way to do it.

$loggedin = (0 or 1) // If it is 0 then one outcome if 1 then it falls onto the next three variables
$status = (0-5) // 4 dead ends
$access = (0-3) // 
$permission = (0-9)

Different combinations of the last two variables result in different outcomes, although some combinations are irrelevant as they are dead ends.

if ($loggedin == 1 && ($status == 1 || $status == 2 ) &&  'whattodohere' ):

I could type all of the combinations manually ($access == 0 && ($var == 2 || $var = 6)) but I am wondering if there is a better way of doing this that I am unaware of.


Solution

  • Have a look at bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] ) - http://php.net/manual/en/function.in-array.php

    Also take a look at range(...) - http://php.net/manual/en/function.range.php

    $status == 1 || $status == 2 [... $status == n] can be reduced to in_array( $status, range(0, $n) )

    Using in_array & range is more costly performance-wise tho, so if you're dead sure you only need to try against 2 different values, use == operator instead.