tags:

views:

43

answers:

4

I'm pretty sure there's an obvious answer for this-- hoping someone can help me--

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_condition is true if condition is true.

Hope that's clear!

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.

+6  A: 

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.

zneak
I'm an idiot. This is what he was asking for, well played. Except change "condition" to "another_condition"
St. John Johnson
+1 for answer just before me :)
Here Be Wolves
+1  A: 

Is this kind of what you are looking for?

while (condition && another_condition) {
   // large block of code
}
if (!condition) {
   // do something else
}
St. John Johnson
That's the way St. John! Thanks man, I'd thought of and tried a do_while loop, but hadn't considered putting two conditions in the statement.Thanks!
julio
julio
+2  A: 

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.

AlexV
+1, "huge block of code" is the problem, not the logic
stereofrog
A: 

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);
jwhat