
Question:
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.
Solution:1
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++; }
Solution:2
This should work:
$i = 0; foreach($posts as $post) { if(++$i > 5) break; ... }
Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
EmoticonEmoticon