Conditional while loop in php?

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

Here is the basic idea:

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

I want a huge block of code to be executed regardless of the state of the condition variable, but only to be executed once if the condition is false and executed as long as another_condition is true if the condition is true.

The following code does not 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!

early.

+3
source share
4

, ?

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

, do ... while():

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

// your code - , .

+8

For readability, if your huge block of code can be divided into several specialized functions, do it. This will certainly pay if you need to debug later.

+3
source

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

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

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

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

or

do {
  hugeBlockOfCode();
} while (another_condition);
+2
source

Source: https://habr.com/ru/post/1736714/


All Articles