Selecting every nth item from an array

后端 未结 8 1986
春和景丽
春和景丽 2021-02-02 13:41

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

8条回答
  •  眼角桃花
    2021-02-02 14:12

    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.

提交回复
热议问题