James
James

Reputation: 43647

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.

Upvotes: 12

Views: 46663

Answers (2)

Pekka
Pekka

Reputation: 449485

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++;
    }

Upvotes: 47

Jenni
Jenni

Reputation: 1706

This should work:

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

Upvotes: 17

Related Questions