[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