How to stop foreach in php

[PHP 4, PHP 5, PHP 7, PHP 8]

break ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1, only the immediate enclosing structure is broken out of.

ei dot dwaps at gmail dot com

1 year ago

You can also use break with parentheses: break[1];

Note:
Using more nesting level leads to fatal error:

There is a variable $posts, which gives an array with many values.

foreach[] is used for output:

foreach[$posts as $post] {
    ...
}

How to show only five first values from $posts?

Like, if we have 100 values, it should give just five.

Thanks.

asked Aug 4, 2010 at 17:41

Use either array_slice[]:

foreach [array_slice[$posts, 0, 5] as $post]
....

or a counter variable and break:

$counter = 0;

foreach [$posts as $post]
 { .....

   if [$counter >= 5] 
    break;

   $counter++;
    }

answered Aug 4, 2010 at 17:43

PekkaPekka

434k137 gold badges965 silver badges1079 bronze badges

0

This should work:

$i = 0;
foreach[$posts as $post] { 
  if[++$i > 5]
    break;
  ... 
} 

answered Aug 4, 2010 at 17:43

JenniJenni

1,6484 gold badges20 silver badges28 bronze badges

0

How do you stop a foreach loop in PHP?

break ¶ break ends execution of the current for , foreach , while , do-while or switch structure. break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of.

How do I close foreach?

If the EXIT statement has the FOREACH statement as its innermost enclosing statement, the FOREACH keyword must immediately follow the EXIT keyword. The EXIT FOREACH statement unconditionally terminates the FOREACH statement, or else returns an error, if no FOREACH statement encloses the EXIT FOREACH statement.

How do you exit a foreach loop if condition is met?

break ends execution of the current for, foreach, while, do-while or switch structure. So yes, you can use it to get out of the foreach loop. Show activity on this post. break statement will break out of the loop.

What is break in PHP?

PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only. The break keyword immediately ends the execution of the loop or switch structure.

Chủ Đề