matleeds Posted November 28, 2011 Share Posted November 28, 2011 Hi, I'd like to know what the best way of breaking out of a nested foreach loop is..but not breaking out of the first foreach ears the code like, foreach ($apts as $apt) { foreach($rdb as $rem) { // Check to see if we've already sent a reminder for this appointment if($apt->id == $rem->appid) { // TODO get out of this foreach and go to the next iterartion of the first foreach } } //rest of 1st foreach code here } is there some syntax i can put at the first foreach eg [here] and reference it within the second foreach continue[here]; or something? thanks, Quote Link to comment Share on other sites More sharing options...
Adam Posted November 28, 2011 Share Posted November 28, 2011 You just need to use break: // Check to see if we've already sent a reminder for this appointment if($apt->id == $rem->appid) { break; } Edit Although your code does seem a little like spaghetti now. It doesn't make much sense why you would break from the child loop if the first ID in the loop matched the parent? Surely you would want to move on to the next iteration, or you should be able to determine this before entering a loop? Quote Link to comment Share on other sites More sharing options...
matleeds Posted November 28, 2011 Author Share Posted November 28, 2011 won't break break out of the second foreach then continue with the remaining code in the first foreach before returning to the next iteration? I don't want to continue with the first foreach's remaining code but go straight to the start of next iteration. apologies if i'm wrong i haven't tried your suggestion yet. Quote Link to comment Share on other sites More sharing options...
Andy-H Posted November 28, 2011 Share Posted November 28, 2011 foreach ($apts as $apt) { foreach($rdb as $rem) { // Check to see if we've already sent a reminder for this appointment if($apt->id == $rem->appid) { continue(2); } } //rest of 1st foreach code here } Quote Link to comment Share on other sites More sharing options...
Psycho Posted November 28, 2011 Share Posted November 28, 2011 Where is this data coming from? If the data is in a database (where it should probably be) then you can get the results you need with an appropriately crafted query rather than looping through all the records like that. Quote Link to comment Share on other sites More sharing options...
ManiacDan Posted November 28, 2011 Share Posted November 28, 2011 Like Andy pointed out, both break and continue accept numerical arguments for the level of control structures you wish to break out of. -Dan Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.