我想遍历一组条件,仅在满足每个条件时才返回 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(这也是不正确的)。
是的,我可以在第一个错误时中断,但是为什么测试失败很重要,并且它可能因不止一个原因而失败,所以我不应该在第一个失败被捕获后立即跳出循环。
有没有办法在不添加另一个变量来统计命中和未命中的情况下做到这一点?
慕容708150