【问题标题】:AND/OR comparisons starting from null, true, or false..?AND/OR 比较从 null、true 或 false 开始......?
【发布时间】:2019-12-31 20:38:21
【问题描述】:

我想遍历一组条件,只有在每个条件都满足时才返回 true,如果不满足则沿途收集原因。

<?php
$dataval = 0;
$tests = [
    [1,0,0,4,5],
    [0,0,0,0,0]
];
foreach($tests as $condition) {
    $retval = null;
    $reasons = [];
    foreach($condition as $item){
       if($item == $dataval){
        $retval == $retval && true;
        } else {
            $retval == $retval && false;
            $reasons[] = "Failed to match " . $dataval . " to " . $item;
        }
    }
    if($retval === true){
        echo "All conditions met<br>";
    } else {
        echo "NOT all conditions met<br>";
    }
    echo "<pre>" . print_r($reasons, 1) . "</pre>";
}

?>

输出

NOT all conditions met
Array
(
    [0] => Failed to match 0 to 1
    [1] => Failed to match 0 to 4
    [2] => Failed to match 0 to 5
)
NOT all conditions met
Array
(
)

无论 $retval 的初始值是多少,一个或两个测试都会失败。如果初始值为真,则两个测试都返回真(这是不正确的);如果为 false 或 null,则两者都返回 false(这也是不正确的)。

是的,我可以打破第一个错误,但为什么测试失败很重要,它失败的原因可能不止一个,所以我不应该只是一旦捕获到第一个故障,就跳出循环。

有没有办法在不添加另一个变量来统计命中和未命中的情况下做到这一点?

【问题讨论】:

  • $retval == $retval &amp;&amp; true; 不可能是正确的,您可能想要$retval = $retval &amp;&amp; true; 而不是实际更改变量$retval
  • $retval == $retval &amp;&amp; false; 就是$retval = false;
  • 由于$retval最初是null,所以当您使用&amp;&amp;分配新值时,它永远不会变成true

标签: php


【解决方案1】:

您需要将$retval 初始化为true。当您遇到不匹配时,将其设置为 false 并将错误推送到 $reason 数组。

但实际上并不需要 $retval 变量。只需检查数组是否为空。

foreach($tests as $condition) {
    $reasons = [];
    foreach($condition as $item){
       if($item != $dataval) {
            $reasons[] = "Failed to match " . $dataval . " to " . $item;
        }
    }
    if(empty($reasons)){
        echo "All conditions met<br>";
    } else {
        echo "NOT all conditions met<br>";
        echo "<pre>" . print_r($reasons, 1) . "</pre>";
    }
}

【讨论】:

  • 我想多了。有时它只需要一双额外的眼睛。谢谢。
猜你喜欢
  • 2021-08-08
  • 2020-12-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 1970-01-01
相关资源
最近更新 更多