how to skip elements in foreach loop

后端 未结 7 1831
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-05 17:56

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?

7条回答
  •  囚心锁ツ
    2020-12-05 18:40

    I'm not sure why you would be using a foreach for this goal, and without your code it's hard to say whether this is the best approach. But, assuming there is a good reason to use it, here's the smallest version I can think of off the top of my head:

    $count = 0;
    foreach( $someArray as $index => $value ){
        if( $count++ < 20 ){
            continue;
        }
    
        // rest of foreach loop goes here
    }
    

    The continue causes the foreach to skip back to the beginning and move on to the next element in the array. It's extremely useful for disregarding parts of an array which you don't want to be processed in a foreach loop.

提交回复
热议问题