如何在'if'中嵌套'for'语句?
问题描述:
在一个PHP项目,我现在的工作,我有类似这样的代码:如何在'if'中嵌套'for'语句?
$allVarsTrue = TRUE;
if ($foo && $bar) {
for ($x=1;$x<=5;$x++) {
if (!somerandomtest($x)) {
$allVarsTrue = FALSE; // if $x fails the test, $allVarsTrue is set to false
}
}
} else { // if either $foo and $bar is false, $allVarsTrue is set to false
$allVarsTrue = FALSE;
}
if ($allVarsTrue) {
echo "True";
} else {
echo "False";
}
我想更简洁地写这篇文章,是这样的
// This code does not work.
if ($foo &&
$bar &&
for ($x=1;$x<=5;$x++) {
somerandomtest($x);
}) {
echo "True";
} else {
echo "False";
}
我怎样才能重写现有的代码更简洁?
答
一种选择是你的循环移动到其自身的功能:
function performTests() {
for(…) { if(!test(…)) return FALSE; } # return early, no need to iterate over remaining items
return TRUE;
}
if($foo && $bar && performTests()) {
…
} else {
…
}
答
你不可能真的。但是,您可以尽快打破在for循环中第一次测试失败
if ($foo && $bar) {
for ($x=1;$x<=5;$x++) {
if (!somerandomtest($x)) {
$allVarsTrue = FALSE; // if $x fails the test, $allVarsTrue is set to false
break; //no point in firther iterating
}
}
} else { // if either $foo and $bar is false, $allVarsTrue is set to false
$allVarsTrue = FALSE;
}
答
把它包在一个函数:
function testStuff($foo, $bar){
if (!$foo || !$bar) {
return FALSE;
}
for ($x=1;$x<=5;$x++) {
if (!somerandomtest($x)) {
return FALSE;
}
}
return TRUE;
}
然后:
if (testStuff($foo, $bar)) {
echo "True";
} else {
echo "False";
}