PHP - 检查给定数量的条件中是否有多个条件为真

问题描述 投票:0回答:7

是否有一种优雅的方法来检查任意给定数量的条件中的多个(但不是全部)条件是否为真?

例如,我有三个变量:$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
7个回答
11
投票

PHP 中的“true”布尔值将转换为整数 1,而“false”则转换为 0。因此:

echo $a + $b +$c;

...如果三个布尔变量

$a
$b
$c
中有两个为 true,则输出 2。 (添加值将隐式地将它们转换为整数。)

这也适用于

array_sum()
等函数,例如:

echo array_sum([true == false, 'cheese' == 'cheese', 5 == 5, 'moon' == 'green cheese']);

...将输出 2.


5
投票

您可以将变量放入数组中,然后使用

array_filter()
count()
来检查真值的数量:

$a = true;
$b = false;
$c = true;

if (count(array_filter(array($a, $b, $c))) == 2) {
    echo "Success";
};

1
投票

我会采用如下方法:

if (evaluate(a, b, c))
{
    do stuff;
}

boolean evaluate(boolean a, boolean b, boolean c) 
{
    return a ? (b || c) : (b && c);
}

它说的是:

  • 如果 a 为真,则 b 或 c 之一也必须为真才能满足 2/3 真实标准。
  • 否则,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 的百分比等于或优于我们想要实现的目标。同样,您可以操纵最终的评估表达式来实现您想要的。


1
投票

这也应该有效,并且可以让您相当轻松地适应这些数字。

$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;
}

0
投票

你可以使用 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
}

0
投票

我认为当你使用运算符“&”、“|”时,写起来有点简单和简短。像这样:

$a = true;
$b = true;
$c = false;

$isTrue = $a&$b | $b&$c | $c&$a;

print_r( $isTrue );

让您自己检查一下:D


0
投票
$atLeastTrue = 2;
$a = true;
$b = true;
$c = false;
print $a + $b + $c >= $atLeastTrue ? 'at least two true' : 'less that two true';
© www.soinside.com 2019 - 2024. All rights reserved.