-1

How can I brake a foreach loop after two iterations, something like this:

foreach($posttags as $tags){     
  $tag1 = $tags->slug;  
} --- this is the first iteration, stored in the variable $tag1

foreach($posttags as $tags){     
  $tag2 = $tags->slug;  
} ---- this is the second iteration, stored in the variable $tag2

brake; --- brake the foreach loop

Any ideas?

webmasters
  • 5,663
  • 14
  • 51
  • 78
  • Couldn't you set both at the same time? – Jared Farrish Nov 09 '11 at 02:09
  • 2
    break may not brake code, but brake will most assuredly not break as expected. –  Nov 09 '11 at 02:09
  • `break` *after* a `foreach`? What is it supposed to break? Also, two *loops* is not the same as two *iterations* in one loop. – deceze Nov 09 '11 at 02:11
  • This may help http://stackoverflow.com/questions/588892/can-you-exit-a-loop-in-php – Doug Owings Nov 09 '11 at 02:11
  • I see I have failed explaining, the code follow a logic – webmasters Nov 09 '11 at 02:12
  • 1
    As written the code will assign the `slug` property of the last element of the `$posttags` array to both `$tag1` and `$tag2`. And then it might produce a warning or error about `break` appearing outside the context of a loop/case. Explain the logic in words or provide an example. – David Harkness Nov 09 '11 at 02:40

1 Answers1

2

The most obvious answer is not to use a foreach loop if you don't want to loop through each item. Use some other looping structure, or grab the first and second items manually if that's what you really want.

DaveB
  • 1,836
  • 1
  • 15
  • 13