tags:

views:

76

answers:

2
+1  Q: 

PHP stop foreach()

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.

+7  A: 

This should work:

$i = 0;
foreach($posts as $post) { 
  if(++$i > 5)
    break;
  ... 
} 
Jenni
+8  A: 

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++;
    }
Pekka
You meant to slice just up to 5 instead of 100, I'm sure.
BoltClock
@BoltClock yes, of course. Thanks, corrected.
Pekka