开发者

Skip a number of iterations during foreach

I would like to skip a number of iterations of a foreach loop.

I have this code;

    $myarray = array("a","b","c","d","e","f","g","h");
    $skip = 5;
    foreach($myarray as $key => $letter){
        if($key < $skip){
            $key = $skip;
        }
        echo $letter;
    }

This code doesn't do the trick. But with it I can sort of explain what I want. I what to actually move the pointer of the next iteration. It thought that by modifying the value of the key to the one i want would be enough. I understand that a possible solution would be this.

    $myarray = array("a","b","c","d","e","f","g","h");
    $skip = 5;
    f开发者_JS百科oreach($myarray as $key => $letter){
        if($key < $skip){
            continue;
        }
        echo $letter;
    }

But that kinda still does the iteration step. I would like to completely jump over the iteration.

Thanks


See: array_slice

$myarray = array("a","b","c","d","e","f","g","h");
foreach(array_slice($myarray, 5) as $key => $letter){
    echo $letter;
}


You could just use a for loop instead

EDIT:

for($i = $skip; $skip > 0, $i < count($myarray); $i++) {
   // do some stuff
}


That's not really how foreach loops (and iteration in general) work.

You can either do the continue version (which works fine; if it's the first thing in the loop body, it's essentially the same), or you can construct a different array to iterate over that doesn't include the first elements, or you can use a regular for loop.


<?php

 $myarray = array("a","b","c","d","e","f","g","h");
    $skip = 5;
    $index = 0 ;
    foreach($myarray as $key => $letter){
        if( ($index % $skip) == 0 ){
           echo $letter;
        }       
        $index++;

    }

?>


$myarray = array("a","b","c","d","e","f","g","h");

foreach (new LimitIterator (new ArrayIterator ($myarray), 5) as $letter)
{
        echo $letter;
}


foreach (array_slice($myarray, 5) as $key => $letter) {
[...]
}


You can call $array->next() for $skip times. There are cases when you cannot easily use a regular for loop: for example when iterating a DatePeriod object.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜