10

This seems like it should be a simple question, but I can't find a good answer. Is there a way of putting a condition on a foreach loop? I'd like something like this:

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

Of course I could just put an if condition inside of the foreach loop as follows:

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

The only thing is that I'd like to stop iterating over the array once the if condition becomes false, for the purpose of improving performance. No need to run through the remainder of the foreach loop to determine that $condition is false once it becomes false.

Any suggestions? Am I misisng something obvious?

Michael.Lumley
  • 2,345
  • 2
  • 31
  • 53
  • 1
    Actually really hope php can have this foreach and while function, that is much clean and tidy – zhihong Nov 11 '14 at 10:56

6 Answers6

24

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

foreach ($array as $value){
  if($condition != true)
    break;
}
nice ass
  • 16,471
  • 7
  • 50
  • 89
  • If `$condition` is boolean, I prefer `if(!$condition)` rather than `if($condition != true)`, otherwise (contains null, ...) I prefer `if($condition !== true)` – safineh Jul 12 '23 at 00:14
4
foreach ($array as $value) {
   if($condition) {
     //do some code
   }
   else {
     break; 
   }
}
Ares
  • 5,905
  • 3
  • 35
  • 51
2

You can easily use the break keyword to exit a foreach loop at the exact moment you wish. this is the simplest way of doing this i can think of at the moment.

foreach ($array as $value)
{
    if($condition == true)
    {
         //do some code
         break; 
    }
}
legrandviking
  • 2,348
  • 1
  • 22
  • 29
2

You could also try a regular for loop, which has a condition built-in. The only thing is that you'll have to access the element of the array 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 complicated example, that stops executing as soon as it finds a fig.

<?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 that helps.

Jay Sheth
  • 1,738
  • 16
  • 15
1

maybe you can use the break; sentence

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

Federico
  • 469
  • 2
  • 15
0

An alternative whitout using foreach but only while. Like this, the loop will end when the condition return false.

$i = 0;
while (condition(array[$i]) === true) {
    $continue = true;
    echo array[i];
    $i++;
}
Whizou
  • 1