Getting foreach to skip over iterations
I basically need something inside a foreach loop that will skip over the first 10 iterations of the array.
foreach($aSubs as $aSub){
if($iStart > '0')
//Skip first 开发者_Python百科$iStart iterations. Start at the next one
}
Thanks
Start a counter and use continue
to skip the first ten loops:
$counter = 0 ;
foreach($aSubs as $aSub) {
if($counter++ < 10) continue ;
// Loop code
}
Using iterators:
$a = array('a','b','c','d');
$skip = 2;
foreach (new LimitIterator(new ArrayIterator($a), $skip) as $e)
{
echo "$e\n";
}
Output:
c
d
Or using the index (if the array has integer keys from 0 .. n-1):
foreach ($a as $i => $e)
{
if ($i < $skip) continue;
echo "$e\n";
}
If $aSubs is a not a object of an class that implements Iterator, and the indexes are sequential integers (starting at zero), it would easier to:
$count = count($aSubs);
for($i = 9, $i < $count; $i++) {
// todo
}
Actually, you don't need to declare another variable $counter
by using the advantage of foreach
loop like this:
foreach ($aSubs as $index => $aSub) {
if ($index < 10) continue;
// Do your code here
}
This is a way better than declaring another variable outside the foreach loop.
精彩评论