在PHP中有条件的while循环?

jul*_*lio 3 php loops while-loop

我需要做一个PHP while循环,但前提是变量为true.而且我不能把while循环放在一个"if"语句中,这似乎是显而易见的事情,因为代码块是巨大的,它将是丑陋和混乱.我是否需要将循环中的代码分解为函数,还是有更简单的方法来处理它?

这是基本的想法:

if(condition){
  while(another_condition){
    //huge block of code loops many times
  }
} else {
  // huge block of code runs once
}
Run Code Online (Sandbox Code Playgroud)

我希望无论条件变量的状态如何都要执行巨大的代码块 - 但是如果condition为false则只执行一次,并且如果condition为true,则执行for another_condition为true.

以下代码不起作用,但提供了我想要完成的内容:

if(condition){ while(another_condition){ }
  // huge block of code
if (condition){ } } // closes the while loop-- obviously throws an error though!
Run Code Online (Sandbox Code Playgroud)

提前致谢.

zne*_*eak 8

如果我正确理解您的问题,您可以使用以下do ... while()结构:

do
{
    // your code
} while(condition);
Run Code Online (Sandbox Code Playgroud)

这将执行// your code一次而不管任何因素,然后仅针对第二次迭代以及之后将检查条件.