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.
There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.
The break statement is one of the looping control keywords in PHP. When program flow comes across break inside while, do while, for as well as foreach loop or a switch construct, remaining statements in the loop/swtich is abandoned and statements after the same will be executed.
At any point within the body of an iteration statement, you can break out of the loop by using the break statement, or step to the next iteration in the loop by using the continue statement.
The continue keyword is used to is used to end the current iteration in a for , foreach , while or do.. while loop, and continues to the next iteration.
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++;
}
This should work:
$i = 0;
foreach($posts as $post) {
if(++$i > 5)
break;
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With