技术PHP-在同一个循环中中断并继续


Technical PHP - break and continue in the same loop

在没有变量的情况下,可以在2个循环中使用break/contence?(无继续2;或中断2;)

示例不起作用:

while(1) {
  // some code
  while(2) {
    // some code
    if(expr) {
      break; // break while(2)
      continue; // continue while(1) but never used
    }
    // some code
  }
  // some code
}

带变量的解决方案:

while(1) {
  // some code
  $continue = false;
  while(2) {
    // some code
    if(expr) {
      $continue = true;
      break;
    }
    // some code
  }
  if($continue) {
    continue;
  }
  // some code
}

在while(2)循环中有中断/继续的解决方案吗?另一种最好的方式?

编辑。数据示例:

for($i=0; $i < 100; $i++) {
    $a = mt_rand(0, 1000);
    for($j=0; $j < 100; $j++) {
      if($j === $a) {
        break; // and continue the first loop
      }
    }
    echo "how to never display this string if second loop break?";
} 

您不需要变量,只需将continue从"while(2)"中去掉即可。如果"expr"为true,则它将中断"while",并继续使用"while。