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 c
A foreach loop provides the fastest iteration over your large array based on comparison testing. I'd stick with something similar to what you have unless somebody wishes to solve the problem with loop unrolling.
This answer should run quicker.
$result = array();
$i = 0;
foreach($source as $value) {
if ($i++ % 205 == 0) {
$result[] = $value;
}
}
I don't have time to test, but you might be able to use a variation of @haim's solution if you first numerically index the array. It's worth trying to see if you can receive any gains over my previous solution:
$result = array();
$source = array_values($source);
$count = count($source);
for($i = 0; $i < $count; $i += 205) {
$result[] = $source[$i];
}
This would largely depend on how optimized the function array_values is. It could very well perform horribly.
You can't move the array pointer, it seems, more than once at a time. I would personally use this:
reset($source);
$next = true;
while($next === true){
$result[] = current($source);
for(i=0;i<205;i++){
$next = next($source);
}
}
If someone can find a function that can move the array pointer more than just one step at a time, you will have a better answer. I think this is good though.
If this really is a bottleneck, you might want to consider rethinking your design in order to make it numerically indexed.
EDIT: Or create and maintain a seperate array with just the 205th items (which gets updated at insert or something like that).
May sound silly but by definition it is fastest since you access memory locations directly and do not perform any comparisons.
I recommend to using array_slice
$count = count($array) ;
for($i=205;$i<$count;$i+=205){
$result[] = array_slice($array,$i,1);
}
If your array was numerically indexed, this would be very fast:
$count = count($array) ;
for($i=205;$i<$count;$i+=205){
$result[] = $array[$i];
}
You could use array_keys
to work only on the array keys.
$keys = array_keys($array);
for ($i=0, $n=min(count($keys), 130000); $i<$n; $i += 205) {
$result[] = $array[$keys[$i]];
}