How to iterate multiple times if multiple conditions are met?

I have an if if statement:

if( (first condition) || (second condition) || (third condition) ){ //line of code } 

If all 3 conditions are met, I want the line of code to be executed 3 times. If only 2 conditions are fulfilled, they must be fulfilled 2 times, etc.

This syntax is also good:

 if(){}elseif(){}elseif(){} 
+5
source share
5 answers

true will be evaluated at 1 and false at 0:

 $qty = (first condition) + (second condition) + (third condition); 

The value of $qty will contain the number of iterations desired.

So, you execute your command, for example:

 for ($i=0; $i<$qty; $i++) { //Your line of code you want to execute, for example: echo $i, "\n"; } 

There are no explicit if-else expressions.

+7
source

You can count the execution numbers first and then use a loop:

 $times = 0; if (first condition) ++$times; if (second condition) ++$times; if (third condition) ++$times; for (... 1 .. $times ...) do_your_thing(); 
+2
source

Usually, if the conditions are short-circuited, this means that if the condition before the other conditions is fulfilled, later ones will never be fulfilled.

Link: http://php.net/manual/en/language.operators.logical.php

So, in your case, I think you should reorganize the code in a different approach, Jeremy Miller's answer seems to be applicable in your case.

+2
source

Here the count variable captures how many conditions are true. And the for loop will execute code equal to that number counts ($ count).

  $count = 0 ; if( first condition ){ $count++; } if( second condition ){ $count++; } if( third condition ){ $count++; } for($i=0;$i<$count;$i++) { //line of code } 
+2
source

You can take one variable all the values โ€‹โ€‹of the conditions. After that run with loop . I think this is a short and best way.

+1
source

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


All Articles