3

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.

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.

4 Answers 4

8

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I'm an idiot. This is what he was asking for, well played. Except change "condition" to "another_condition"
3

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.

Comments

2

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

Comments

1

Is this kind of what you are looking for?

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

2 Comments

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!
oh, so I guess the way it look is like this: do { // huge code block } while (condition && another_condition) so if condition is false, it only executes once._

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.