PHP stop foreach ()

There is a variable $poststhat gives an array with many values.

foreach() used to output:

foreach($posts as $post) {
    ...
}

How to show only the first five values ​​from $posts?

For example, if we have 100 values, this should give only five.

Thank.

+5
source share
2 answers

Use array_slice():

foreach (array_slice($posts, 0, 5) as $post)
....

or counting variable and break:

$counter = 0;

foreach ($posts as $post)
 { .....

   if ($counter >= 5) 
    break;

   $counter++;
    }
+20
source

This should work:

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

All Articles