Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to skip some records in a foreach loop.

For example, there are 68 records in the loop. How can I skip 20 records and start from record #21?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
390 views
Welcome To Ask or Share your Answers For Others

1 Answer

Five solutions come to mind:

Double addressing via array_keys

The problem with for loops is that the keys may be strings or not continues numbers therefore you must use "double addressing" (or "table lookup", call it whatever you want) and access the array via an array of it's keys.

// Initialize 25 items
$array = range( 1, 25, 1);

// You need to get array keys because it may be associative array
// Or it it will contain keys 0,1,2,5,6...
// If you have indexes staring from zero and continuous (eg. from db->fetch_all)
// you can just omit this
$keys = array_keys($array);
for( $i = 21; $i < 25; $i++){
    echo $array[ $keys[ $i]] . "
";
    // echo $array[$i] . "
"; // with continuous numeric keys
}


Skipping records with foreach

I don't believe that this is a good way to do this (except the case that you have LARGE arrays and slicing it or generating array of keys would use large amount of memory, which 68 is definitively not), but maybe it'll work: :)

$i = 0;
foreach( $array as $key => $item){
    if( $i++ < 21){
        continue;
    }
    echo $item . "
";
}


Using array slice to get sub part or array

Just get piece of array and use it in normal foreach loop.

$sub = array_slice( $array, 21, null, true);
foreach( $sub as $key => $item){
    echo $item . "
";
}


Using next()

If you could set up internal array pointer to 21 (let's say in previous foreach loop with break inside, $array[21] doesn't work, I've checked :P) you could do this (won't work if data in array === false):

while( ($row = next( $array)) !== false){
  echo $row;
}

btw: I like hakre's answer most.


Using ArrayIterator

Probably studying documentation is the best comment for this one.

// Initialize array iterator
$obj = new ArrayIterator( $array);
$obj->seek(21); // Set to right position
while( $obj->valid()){ // Whether we do have valid offset right now
    echo $obj->current() . "
";
    $obj->next(); // Switch to next object
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...