如果我有声明:
$a = 1;
$b = 2;
$c = 3;
if($a == 1 && $b == 2 && $c == 3)
{
echo 'correct';
}
else
{
echo 'what variable's weren't matched';
}
有没有办法知道什么不看,而不是单独写一切?
干杯!
答案 0 :(得分:2)
没有。你的表达式变成了一个布尔值,所以除了再次检查相等之外,你无法找出哪个触发了“假”。
答案 1 :(得分:2)
您需要单独测试每个,但您可以执行以下操作:
$a = 1;
$b = 2;
$c = 3;
$a_matched = $a == 1;
$b_matched = $b == 1;
$c_matched = $c == 1;
if($a_matched && $b_matched && $c_matched)
{
echo 'correct';
}
else
{
if (!$a_matched) echo 'a did not match!';
if (!$b_matched) echo 'b did not match!';
if (!$c_matched) echo 'c did not match!';
}
但这不仅仅是:
$a = 1;
$b = 2;
$c = 3;
if($a == 1 && $b == 2 && $c == 3)
{
echo 'correct';
}
else
{
if (!$a == 1) echo 'a did not match!';
if (!$b == 2) echo 'c did not match!';
if (!$c == 3) echo 'b did not match!';
}
答案 2 :(得分:2)
实际上,嘿,我收回我的评论。您可以依赖布尔短路来设置一个变量,指示条件的最后一部分是真的:
if (($x = 'a') && $a == 1 && ($x = 'b') && $b == 2 && ($x = 'c') && $c == 3) {
echo "correct\n";
} else {
echo "$x is wrong\n";
}
注意,我绝不会在生产代码中写这个,因为它很傻,很难理解应该发生什么。但至少可以玩弄乐趣。
答案 3 :(得分:0)
都能跟得上!那是不可能的。但是,通过使用数组,您可以简化生活:
$results = array(1, 2, 4);
$expected = array(1, 2, 3);
$count = count($results);
$wrong = array();
for($i = 0; $i < $count; $i++) {
if($results[$i] !== $expected[$i]) {
$wrong[] = $i;
}
}
if(count($wrong) > 0) {
echo "There were wrong ones. They were at positions: " . implode(', ', $wrong);
} else {
echo "All good!";
}
例如。