是否有一种优雅的方法来检查在任何给定数量的条件中是否有多个(但不是全部)条件为真?
例如,我有三个变量:$a、$b和$c。我想检验其中任意两个是否为真。所以下面的代码会传递:
$a = true;
$b = false;
$c = true;
但这不会:
$a = false;
$b = false;
$c = true;
同样,我可能想检查7个条件中的4个是否为真,例如。
我意识到我可以检查每个组合,但随着条件数量的增加,这将变得更加困难。循环遍历条件并保持记录是我能想到的最佳选择,但我认为可能有另一种方法可以做到这一点。
谢谢!
编辑:谢谢你所有的好答案,他们非常感激。如果变量不是显式布尔值会怎样呢?例如($a == 2)
($b != "cheese")
($c !== false)
($d instanceof SomeClass)
PHP中的"true"布尔值将转换为整数1,而"false"将转换为0。因此:
echo $a + $b +$c;
…如果三个布尔变量$a
, $b
或$c
中有两个为真,则输出2。(添加值将隐式地将其转换为整数。)
这也适用于array_sum()
这样的函数,例如:
echo array_sum([true == false, 'cheese' == 'cheese', 5 == 5, 'moon' == 'green cheese']);
…将输出2.
您可以将变量放入数组中,并使用array_filter()
和count()
来检查真值的数量:
$a = true;
$b = false;
$c = true;
if (count(array_filter(array($a, $b, $c))) == 2) {
echo "Success";
};
我会选择如下方法:
if (evaluate(a, b, c))
{
do stuff;
}
boolean evaluate(boolean a, boolean b, boolean c)
{
return a ? (b || c) : (b && c);
}
它说的是:
- 如果a为True,则b或c中的一个也必须为True,以符合2/3真正的标准。
- Else, b和c必须都为真!
如果你想扩展和自定义条件和变量的数量,我会选择如下的解决方案:
$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);
简单地说,我们计算true的值,并确保true的百分比等于或优于我们想要达到的值。同样,您可以操作最终的求值表达式来实现您想要的结果。
这应该也可以,并且可以让您相当容易地调整到数字。
$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;
}
你可以使用while循环:
$condition_n = "x number"; // number of required true conditions
$conditions = "x number"; // number of conditions
$loop = "1";
$condition = "0";
while($loop <= $conditions)
{
// check if condition is true
// if condition is true : $condition = $condition + 1;
// $loop = $loop + 1;
}
if($condition >= $condition_n)
{
// conditions is True
}
else
{
// conditions is false
}
我认为当你使用运算符"&"时,这是一个简单而简短的写作。, "|"像这样:
$a = true;
$b = true;
$c = false;
$isTrue = $a&$b | $b&$c | $c&$a;
print_r( $isTrue );
让你自己检查:D