Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining foreach and while in PHP

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?

like image 267
Michael.Lumley Avatar asked Sep 16 '13 17:09

Michael.Lumley


2 Answers

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

foreach ($array as $value){
  if($condition != true)
    break;
}
like image 53
nice ass Avatar answered Oct 11 '22 09:10

nice ass


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; 
    }
}
like image 37
legrandviking Avatar answered Oct 11 '22 09:10

legrandviking