限制数组中的项目数

Pau*_*ert 3 php

我有一个通过foreach循环处理的数组.

foreach($images as $imageChoices) {
    Do stuff here
}
Run Code Online (Sandbox Code Playgroud)

如何限制循环只处理数组中的前4项?

sal*_*the 10

array_slice()可以使用该功能.

foreach(array_slice($images, 0, 4) as $imageChoices) { … }
Run Code Online (Sandbox Code Playgroud)

这使您只能循环遍历所需的值,而无需计算到目前为止已完成的数量.