dqm83011
2012-01-27 09:02 阅读 27
已采纳

如何在'if'中嵌套'for'语句?

In a PHP project I am working on right now, I have some code similar to this:

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

I would like to write this more succinctly, something like this

// This code does not work.
if ($foo &&
    $bar &&
    for ($x=1;$x<=5;$x++) {
      somerandomtest($x);
    }) {
  echo "True";
} else {
  echo "False";
}

How can I rewrite the existing code more succinctly?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

3条回答 默认 最新

  • 已采纳
    dongmi6102 dongmi6102 2012-01-27 09:09

    One option is to move your loop into its own function:

    function performTests() {
      for(…) { if(!test(…)) return FALSE; } # return early, no need to iterate over remaining items
      return TRUE;
    }
    
    if($foo && $bar && performTests()) {
      …
    } else {
      …
    }
    
    点赞 评论 复制链接分享
  • duanjia2772 duanjia2772 2012-01-27 09:06

    You can't really. However, you can break the for loop as soon as first test is failed

    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; 
    }
    
    点赞 评论 复制链接分享
  • duanmen8491 duanmen8491 2012-01-27 09:10

    Wrap it in a function:

    function testStuff($foo, $bar){
        if (!$foo || !$bar) {
            return FALSE;
        }
        for ($x=1;$x<=5;$x++) {
            if (!somerandomtest($x)) {
                return FALSE;
            }
        }
        return TRUE;
    }
    

    And then:

    if (testStuff($foo, $bar)) {
      echo "True";
    } else {
      echo "False";
    }
    
    点赞 评论 复制链接分享

相关推荐