|
|
PHP; break inner loop & continue outer loop on condition
|
|
|
|
Grizzled Veteran
Join Date: Oct 2003
Status:
Offline
|
|
Ok I have an outer and inner loop. If some condition is met in the inner loop, I want to break it and continue the outer loop from the beginning (roll it over to the next entry).
I have come up with the following method using break on the inner loop if the condition is met and continue on the outer loop immediately after the inner loop if the condition is met. It works fine, but I'm just wondering if there is something built into PHP to do this (I could not find anything).
Here is an example pseudo code incase that was too difficult to follow:
[php]//outer loop
foreach ($outer_array as $outer) {
// some other code here
.....
// inner loop
foreach ($inner_array as $inner) {
// some other code here
.....
// if conditions is true, break this loop
if ($condition == true) {
break;
}
}
// if condition is true, continue this loop
if ($condition == true) {
continue;
}
// some other code here
.....
}[/php]
This works I know, but am just wondering if there is an easier way to do it.
|
The only thing necessary for evil to flourish is for good men to do nothing
- Edmund Burke
|
|
|
|
|
|
|
|
Mac Elite
Join Date: Dec 2001
Location: Atlanta, GA, USA
Status:
Offline
|
|
I think the way you did it is correct. You could change the foreach to a while loop to test the condition, but it's really no more efficient.
|
Mac Pro 2x 2.66 GHz Dual core, Apple TV 160GB, two Windows XP PCs
|
|
|
|
|
|
|
|
Grizzled Veteran
Join Date: Oct 2003
Status:
Offline
|
|
Thanks... really I just wanted to make sure I was not overlooking some built in function or call that would do the same thing as breaking current loop and immediately continuing outer loop.
|
The only thing necessary for evil to flourish is for good men to do nothing
- Edmund Burke
|
|
|
|
|
|
|
|
Grizzled Veteran
Join Date: Jun 2001
Location: Melbourne, Australia
Status:
Offline
|
|
Originally Posted by madmacgames
Thanks... really I just wanted to make sure I was not overlooking some built in function or call that would do the same thing as breaking current loop and immediately continuing outer loop.
I think you can simplify this with:-
Code:
//outer loop
foreach ($outer_array as $outer) {
// some other code here
.....
// inner loop
foreach ($inner_array as $inner) {
// some other code here
.....
// if conditions is true, break this loop
if ($condition == true) {
continue 2;
}
}
// some other code here
.....
}
The continue with the optional argument allows you to skip to the end of the the specified number of nested loops.
|
Computer thez nohhh...
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Forum Rules
|
|
|
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts
|
HTML code is Off
|
|
|
|
|
|
|
|
|
|
|
|