Combining foreach and while in PHP

This seems to be a simple question, but I cannot find a good answer. Is there a way to put a condition on a foreach loop? I would like something like this:

foreach ($array as $value WHILE $condition == true) { //do some code } 

Of course, I could just put an if condition inside the foreach loop like this:

 foreach ($array as $value) { if($condition == true) {//do some code} } 

The only thing I would like to stop the repetition of the array after the if condition becomes false, in order to improve performance. You do not have to go through the remainder of the foreach loop to determine that the condition is $ false when it becomes false.

Any suggestions? Is there something obvious?

+6
source share
5 answers

No, but you can break loop when your condition is met:

 foreach ($array as $value){ if($condition != true) break; } 
+17
source

You can easily use the break keyword to exit the foreach loop the moment you want. this is the easiest way to do this that I can think of at the moment.

 foreach ($array as $value) { if($condition == true) { //do some code break; } } 
+2
source

You can also try a regular loop that has a built-in condition. The only thing you need to access the element of the array is using its index.

 <?php //Basic example of for loop $fruits = array('apples', 'figs', 'bananas'); for( $i = 0; $i < count($fruits); $i++ ){ $fruit = $fruits[$i]; echo $fruit . "\n"; } 

This is a slightly more complex example that stops executing as soon as it finds a drawing.

 <?php //Added condition to for loop $fruits = array('apple', 'fig', 'banana'); $continue = true; for( $i = 0; $i < count($fruits) && $continue == true; $i++ ){ $fruit = $fruits[$i]; if( $fruit == 'fig' ){ $continue = false; } echo $fruit . "\n"; } 

I hope this helps.

+2
source
 foreach ($array as $value) { if($condition) { //do some code } else { break; } } 
+2
source

perhaps you can use the break clause;

foreach ($ array as $ value) {if ($ condition == true) {// make some code} more {break;}}

+1
source

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


All Articles