-
December 16th, 2011, 02:24 PM
#1
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.
-
December 17th, 2011, 09:05 AM
#2
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?
-
December 19th, 2011, 09:33 AM
#3
Re: Breaking out of two foreach loops?
Wow, that is awesome. Thanks for the tip.
-
December 20th, 2011, 12:01 AM
#4
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|