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?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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.
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: 🙂
Using array slice to get sub part or array
Just get piece of array and use it in normal foreach loop.
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):btw: I like hakre’s answer most.
Using
ArrayIteratorProbably studying documentation is the best comment for this one.