Gabriel Spiteri Gabriel Spiteri - 25 days ago 8
PHP Question

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

Answer Source

You could just use a for loop instead

EDIT:

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