dqm83011 2012-01-27 09:02
浏览 135
已采纳

如何在'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 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 {
      …
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件