Gabriel Spiteri
Gabriel Spiteri

Reputation: 4978

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;
    foreach($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

Upvotes: 1

Views: 1492

Answers (7)

Marco Marsala
Marco Marsala

Reputation: 2462

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.

Upvotes: 0

rabudde
rabudde

Reputation: 7722

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

Upvotes: 0

Andreas Wong
Andreas Wong

Reputation: 60516

You could just use a for loop instead

EDIT:

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

Upvotes: 1

akond
akond

Reputation: 16035

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

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

Upvotes: 0

DhruvPathak
DhruvPathak

Reputation: 43235

<?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++;

    }

?>

Upvotes: 0

Yoshi
Yoshi

Reputation: 54649

See: array_slice

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

Upvotes: 2

Amber
Amber

Reputation: 526573

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.

Upvotes: 0

Related Questions