What would be the most efficient way to select every nth item from a large array? Is there a 'smart' way to do it or is looping the only way?
Some points to consider:
- The array is quite large with 130 000 items
- I have to select every 205th item
- The items are not numerically indexed, so
for($i = 0; $i <= 130000; $i += 205)
won't work
So far, this is the most efficient method I've come up with:
$result = array();
$i = 0;
foreach($source as $value) {
if($i >= 205) {
$i = 0;
}
if($i == 0) {
$result[] = $value;
}
$i++;
}
Or the same with modulo:
$result = array();
$i = 0;
foreach($source as $value) {
if($i % 205 == 0) {
$result[] = $value;
}
$i++;
}
These methods can be quite slow, is there any way to improve? Or am I just splitting hairs here?
EDIT
Good answers all around with proper explanations, tried to pick the most fitting as the accepted answer. Thanks!