Jump to content

Recommended Posts

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,

Link to comment
https://forums.phpfreaks.com/topic/251973-break-out-of-nested-foreach/
Share on other sites

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?

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.

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
      }

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.