我有一个通过foreach
循环处理的数组。
foreach($images as $imageChoices) {
Do stuff here
}
如何将循环限制为仅处理数组中的前4项?
答案 0 :(得分:10)
可以使用array_slice()
功能。
foreach(array_slice($images, 0, 4) as $imageChoices) { … }
这使您只能循环遍历所需的值,而无需计算到目前为止已完成的数量。
答案 1 :(得分:2)
您基本上使用$i
计算每次迭代,并在达到4时使用break
停止循环...
$i = 0;
foreach($images as $imageChoices) {
//Do stuff here
$i++;
if($i >= 4 { break; }
}
答案 2 :(得分:1)
你可以这样做:
for($i=0; $i<count($images) && $i<4; $i++) {
// Use $images[$i]
}
答案 3 :(得分:1)
使用计数器变量并增加每个循环的计数。
根据计数器值进行检查
如下所示:
$count=1;
foreach($images as $imageChoices) {
if($count <=4)
{
Do stuff here
}
else
{
Jump outside of loop break;
}
$count++;
}
或者您可以使用for loop
代替foreach
,也可以使用一些内置的PHP Array
函数
for($i=0; $i<4; $i++) {
// Use $images[$i]
}
答案 4 :(得分:0)
function process()
{
//Some stuff
}
process(current($imageChoices));
process(next($imageChoices));
process(next($imageChoices));
process(next($imageChoices));