Reputation: 773
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.
Upvotes: 0
Views: 143
Reputation: 5520
An approach could to be to use switch(): http://php.net/manual/en/control-structures.switch.php
Example:
<?php
/*
$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) */
$access = 1;
$loggedin = 1;
$status = 1;
if ($loggedin == 1) {
if ($status == 1 || $status == 2 ) {
switch($access) {
case 0:
//do some coding
break;
case 1:
echo 'ACCESSS 1';
//do some coding
break;
default:
//Do some coding here when $access is issued in the cases above
break;
}
}
}
else {
//Do coding when $loggedIn = 0
}
?>
In the example ACCESS 1 would be the output.
Maybe you could also do some math and compare the result (in some circumstances depending on what you want to achieve). For example:
<?php
$permission = 1;
$access = 2;
$result = $permission * $access;
if ($result > 0) {
switch($result) {
case 0:
//do something
break;
case 1:
//do something
break;
default:
//Do something when value of $result not issued in the cases above
}
}
?>
Upvotes: 1
Reputation: 2648
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.
Upvotes: 1