开发者

conditional while loop in php?

开发者 https://www.devze.com 2022-12-22 23:29 出处:网络
I need to do a PHP while loop, but only if a variable is true. And I can\'t really put the while loop in an \"if\" statement, which seems like the obvious thing to do, since the code block is huge and

I need to do a PHP while loop, but only if a variable is true. And I can't really put the while loop in an "if" statement, which seems like the obvious thing to do, since the code block is huge and it would be ugly and confusing. Do I need to break out the code in the loop into a function, or is there an easier way to deal with this?

Here's the basic idea:

if(condition){
  while(another_condition){
    //huge block of code loops many times
  }
} else {
  // huge block of code runs once
}

I want the huge block of code to execute regardless of the state of the condition variable-- but only to execute once if condition is false, and execute for as long as another_condit开发者_运维百科ion is true if condition is true.

The following code doesn't work, but gives an idea of what I want to accomplish:

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

thanks in advance.


If I understood your problem correctly, you could use the do ... while() structure:

do
{
    // your code
} while(condition);

This will execute // your code once regardless of any factor, and then only for the second iteration and those after will it check for the condition.


For readability if your huge block of code can be separated in several specialized functions, do it. It will surely pay out if you need to debug later.


I would put the huge block of code in a function so it can be used again without having duplicate code.

function hugeBlockOfCode() {
  // Huge block of code.
}

while (condition && another_condition) {
  hugeBlockOfCode();
}

if (!condition) {
  // Run code once.
  hugeBlockOfCode();
}

or

do {
  hugeBlockOfCode();
} while (another_condition);


Is this kind of what you are looking for?

while (condition && another_condition) {
   // large block of code
}
if (!condition) {
   // do something else
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号