146

I am looking to break an outer for/foreach loop in PHP.

This can be done in ActionScript like so:

top : for each(var i:MovieClip in movieClipArray)
{
    for each(var j:String in nameArray)
    {
        if(i.name == j) break top;
    }
}

What's the PHP equivalent?

Athari
  • 33,702
  • 16
  • 105
  • 146
Marty
  • 39,033
  • 19
  • 93
  • 162

6 Answers6

318

In the case of 2 nested loops:

break 2;

http://php.net/manual/en/control-structures.break.php

lucian303
  • 3,483
  • 1
  • 17
  • 11
43

PHP Manual says

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

break 2;
Shakti Singh
  • 84,385
  • 21
  • 134
  • 153
22

You can using just a break-n statement:

foreach(...)
{
    foreach(...)
    {
        if (i.name == j) 
            break 2; //Breaks 2 levels, so breaks outermost foreach
    }
}

If you're in php >= 5.3, you can use labels and gotos, similar as in ActionScript:

foreach (...)
{        
    foreach (...)
    {
        if (i.name == j) 
            goto top;
    }
}
top:

But goto must be used carefully. Goto is evil (considered bad practice)

Nik
  • 2,885
  • 2
  • 25
  • 25
Edgar Villegas Alvarado
  • 18,204
  • 2
  • 42
  • 61
13

You can use break 2; to break out of two loops at the same time. It's not quite the same as your example with the "named" loops, but it will do the trick.

Jon
  • 428,835
  • 81
  • 738
  • 806
7
$i = new MovieClip();
foreach ($movieClipArray as $i)
{
    $nameArray = array();
    foreach ($nameArray as $n) 
        if ($i->name == $n) 
            break 2;
}
Nik
  • 2,885
  • 2
  • 25
  • 25
Jordan Arsenault
  • 7,100
  • 8
  • 53
  • 96
  • Nice try at converting the entire supplied code to PHP, though the break statement doesn't do what I need it to do (it only ends the inner loop). – Marty May 04 '11 at 08:18
  • refresh you page :) I replaced with _break 2_ ... which according to PHP Manual: "break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. " – Jordan Arsenault May 04 '11 at 08:22
6

Use goto?

for ($i = 0, $j = 50; $i < 100; $i++) 
{
  while ($j--) 
  {
    if ($j == 17) 
      goto end; 
  }  
}
echo "i = $i";
end:
echo 'j hit 17';
Nik
  • 2,885
  • 2
  • 25
  • 25
Petr Abdulin
  • 33,883
  • 9
  • 62
  • 96
  • 4
    I know this is a 10-year-old answer but goto was never the right answer. If it's 2021+ and you are reading this, please, never use goto! – nickpapoutsis Feb 07 '21 at 05:04
  • 3
    Even the manual itself warns against it: https://www.php.net/manual/en/control-structures.goto.php – blues Aug 31 '21 at 08:35