Php 如何在“if”中嵌套“for”语句?
在我目前正在进行的一个PHP项目中,我有一些类似的代码:Php 如何在“if”中嵌套“for”语句?,php,if-statement,for-loop,Php,If Statement,For Loop,在我目前正在进行的一个PHP项目中,我有一些类似的代码: $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 eith
$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";
}
如何更简洁地重写现有代码?你真的不能。但是,您可以在第一次测试失败后立即中断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;
}
你真的不能。但是,您可以在第一次测试失败后立即中断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 performTests() {
for(…) { if(!test(…)) return FALSE; } # return early, no need to iterate over remaining items
return TRUE;
}
if($foo && $bar && performTests()) {
…
} else {
…
}
function testStuff($foo, $bar){
if (!$foo || !$bar) {
return FALSE;
}
for ($x=1;$x<=5;$x++) {
if (!somerandomtest($x)) {
return FALSE;
}
}
return TRUE;
}
一个选项是将循环移动到它自己的函数中:
function performTests() {
for(…) { if(!test(…)) return FALSE; } # return early, no need to iterate over remaining items
return TRUE;
}
if($foo && $bar && performTests()) {
…
} else {
…
}
function testStuff($foo, $bar){
if (!$foo || !$bar) {
return FALSE;
}
for ($x=1;$x<=5;$x++) {
if (!somerandomtest($x)) {
return FALSE;
}
}
return TRUE;
}
将其包装在函数中:
function performTests() {
for(…) { if(!test(…)) return FALSE; } # return early, no need to iterate over remaining items
return TRUE;
}
if($foo && $bar && performTests()) {
…
} else {
…
}
function testStuff($foo, $bar){
if (!$foo || !$bar) {
return FALSE;
}
for ($x=1;$x<=5;$x++) {
if (!somerandomtest($x)) {
return FALSE;
}
}
return TRUE;
}
将其包装在函数中:
function performTests() {
for(…) { if(!test(…)) return FALSE; } # return early, no need to iterate over remaining items
return TRUE;
}
if($foo && $bar && performTests()) {
…
} else {
…
}
function testStuff($foo, $bar){
if (!$foo || !$bar) {
return FALSE;
}
for ($x=1;$x<=5;$x++) {
if (!somerandomtest($x)) {
return FALSE;
}
}
return TRUE;
}