2012-01-27 147 views
1

在一個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"; 
} 

我怎樣才能重寫現有的代碼更簡潔?

回答

4

一種選擇是你的循環移動到其自身的功能:

function performTests() { 
    for(…) { if(!test(…)) return FALSE; } # return early, no need to iterate over remaining items 
    return TRUE; 
} 

if($foo && $bar && performTests()) { 
    … 
} else { 
    … 
} 
0

你不可能真的。但是,您可以儘快打破在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; 
} 
3

把它包在一個函數:

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"; 
}