[英]PHP - Check if more than one condition is true in a given number of conditions
有沒有一種優雅的方法來檢查在任何給定數量的條件下是否存在多個但不是所有條件?
例如,我有三個變量:$ 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 = 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);
簡單地說,我們評估真實情況,並確保真實百分比等於或優於我們想要實現的目標。 同樣,您可以操縱最終的評估表達式來實現您想要的效果。
這也應該有效,並且可以讓您相當容易地調整數字。
$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;
}
當你使用運算符“&”,“|”時,我認為這是一個簡單易懂的寫作 像這樣:
$a = true;
$b = true;
$c = false;
$isTrue = $a&$b | $b&$c | $c&$a;
print_r( $isTrue );
讓我們自己檢查:D
你可以使用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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.