PHP:限制 foreach() 语句?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1656969/
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
PHP: Limit foreach() statement?
提问by tarnfeld
How can i limit a foreach() statement? Say i only want it to run the first 2 'eaches' or something?
如何限制 foreach() 语句?说我只希望它运行前 2 个 'eaches' 之类的?
回答by reko_t
There are many ways, one is to use a counter:
方法很多,一种是使用计数器:
$i = 0;
foreach ($arr as $k => $v) {
/* Do stuff */
if (++$i == 2) break;
}
Other way would be to slice the first 2 elements, this isn't as efficient though:
另一种方法是对前 2 个元素进行切片,但这并不那么有效:
foreach (array_slice($arr, 0, 2) as $k => $v) {
/* Do stuff */
}
You could also do something like this (basically the same as the first foreach, but with for):
你也可以做这样的事情(与第一个 foreach 基本相同,但使用 for):
for ($i = 0, reset($arr); list($k,$v) = each($arr) && $i < 2; $i++) {
}
回答by Valentin Golev
You can either use
您可以使用
break;
or
或者
foreach() if ($tmp++ < 2) {
}
(the second solution is even worse)
(第二种解决方案更糟糕)
回答by RageZ
回答by Tgr
In PHP 5.5+, you can do
在 PHP 5.5+ 中,你可以这样做
function limit($iterable, $limit) {
foreach ($iterable as $key => $value) {
if (!$limit--) break;
yield $key => $value;
}
}
foreach (limit($arr, 10) as $key => $value) {
// do stuff
}
Generatorsrock.
发电机摇滚。
回答by tcgumus
this is best solution for me :)
这对我来说是最好的解决方案:)
$i=0;
foreach() if ($i < yourlimitnumber) {
$i +=1;
}

