PHP 停止 foreach()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3408188/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:38:21  来源:igfitidea点击:

PHP stop foreach()

phpcountforeach

提问by James

There is a variable $posts, which gives an array with many values.

有一个变量$posts,它给出了一个包含许多值的数组。

foreach()is used for output:

foreach()用于输出:

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

How to show only five first values from $posts?

如何仅显示来自 的五个第一个值$posts

Like, if we have 100 values, it should give just five.

比如,如果我们有 100 个值,它应该只给出 5 个。

Thanks.

谢谢。

回答by Pekka

Use either array_slice():

使用任一 array_slice():

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

or a counter variable and break:

或计数器变量和break

$counter = 0;

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

   if ($counter >= 5) 
    break;

   $counter++;
    }

回答by Jenni

This should work:

这应该有效:

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