CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2009
    Posts
    1,689

    Breaking out of two foreach loops?

    What is the proper way to break out of two or more foreach loops? break obviously won't work. I could add a flag that is set before the first break and checked before each loop, but that seems really inelegant.

    I am currently using the old calling card of the devil: goto

    Code:
    foreach($something as $foo){
       foreach($foo as $bar){
          if ($bar == 'whatever') goto sixsixsix;
       }
    }
    sixsixsix:
    What is the proper way to do this? I'm used to C++ where we don't have foreach and use custom conditions.

    Last edited by ninja9578; December 16th, 2011 at 02:28 PM.

  2. #2
    Join Date
    Jan 2009
    Posts
    596

    Re: Breaking out of two foreach loops?

    You're in luck - in PHP, 'break' can take a numeric argument telling it how many nested structures to break out of. These can be any of for, foreach, while, or switch.

    So in your case,
    Code:
    foreach($something as $foo){
       foreach($foo as $bar){
          if ($bar == 'whatever') break 2; <-- breaks out of both loops
       }
    }
    Useful, isn't it?

  3. #3
    Join Date
    Jan 2009
    Posts
    1,689

    Re: Breaking out of two foreach loops?

    Wow, that is awesome. Thanks for the tip.

  4. #4
    Join Date
    Dec 2011
    Posts
    1

    Re: Breaking out of two foreach loops?

    Nice! New to this forum, hope I'd learn more tricks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured