Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP stop foreach()

Tags:

foreach

php

count

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.

like image 576
James Avatar asked Aug 04 '10 17:08

James


People also ask

How do you stop a foreach loop?

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.

What is break in PHP?

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.

How do you stop a foreach loop in C#?

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.

What is continue in PHP?

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.


2 Answers

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++;
    }
like image 68
Pekka Avatar answered Sep 30 '22 18:09

Pekka


This should work:

$i = 0;
foreach($posts as $post) { 
  if(++$i > 5)
    break;
  ... 
} 
like image 21
Jenni Avatar answered Sep 30 '22 16:09

Jenni