Is there an elegant way to check if multiple, but not all, conditions are true out of any given number of conditions?
For example, I have three variables: $a, $b, and $c. I want to check that any two of these are true. So the following would pass:
$a = true;
$b = false;
$c = true;
But this wouldn't:
$a = false;
$b = false;
$c = true;
Also, I may want to check if 4 out of 7 conditions were true, for example.
I realise I can check each combination, but this would get more difficult as the number of conditions increased. Looping through the conditions and keeping a tally is the best option I can think of, but I thought there may be a different way to do this.
Thanks!
Edit: Thanks for all the great answers, they're much appreciated. Just to throw a spanner in to the works, what if the variables weren't explicit booleans? E.g.
($a == 2)
($b != "cheese")
($c !== false)
($d instanceof SomeClass)
A "true" boolean in PHP casts to a 1 as an integer, and "false" casts to 0. Hence:
echo $a + $b +$c;
...will output 2 if two out of the three boolean variables $a
, $b
or $c
are true. (Adding the values will implicitly convert them to integers.)
This will also work with functions like array_sum()
, so for example:
echo array_sum([true == false, 'cheese' == 'cheese', 5 == 5, 'moon' == 'green cheese']);
...will output 2.
You could put your variables in an array, and use array_filter()
and count()
to check the number of true values:
$a = true;
$b = false;
$c = true;
if (count(array_filter(array($a, $b, $c))) == 2) {
echo "Success";
};
I'd go for a method like the following:
if (evaluate(a, b, c))
{
do stuff;
}
boolean evaluate(boolean a, boolean b, boolean c)
{
return a ? (b || c) : (b && c);
}
What it says is:
If you want to expand and customise the conditions and the number of variables I'd go for for a solution like the following:
$a = true;
$b = true;
$c = true;
$d = false;
$e = false;
$f = true;
$condition = 4/7;
$bools = array($a, $b, $c, $d, $e, $f);
$eval = count(array_filter($bools)) / sizeof($bools);
print_r($eval / $condition >= 1 ? true : false);
Simply we evaluate the true's and we make sure that the % of True is equals or is better than what we want to achieve. Likewise you could manipulate the final evaluation expression to achieve what you want.
This should also work, and would allow you fairly easily to adjust to the numbers.
$a = array('soap','soap');
$b = array('cake','sponge');
$c = array(true,true);
$d = array(5,5);
$e = false;
$f = array(true,true);
$g = array(false,true);
$pass = 4;
$ar = array($a,$b,$c,$d,$e,$f,$g);
var_dump(trueornot($ar,$pass));
function trueornot($number,$pass = 2){
$store = array();
foreach($number as $test){
if(is_array($test)){
if($test[0] === $test[1]){
$store[] = 1;
}
}else{
if(!empty($test)){
$store[] = 1;
}
}
if(count($store) >= $pass){
return TRUE;
}
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With