-1

I have an array like this: (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10). I want to keep the first three (0, 1, 2), then remove the next two (that is 3, 4), then keep three (6, 7, 8), then remove two (9, 10) until the array is completely looped through.

I'm sure there is an easy solution that i'm just not seeing!

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
  • 1
    Possible duplicate of [Delete an element from an array](http://stackoverflow.com/questions/369602/delete-an-element-from-an-array) – Will Barnwell Apr 03 '17 at 16:24

2 Answers2

0

Quite a few options for that, the cleanest code might be:

$array = [0,1,2,3,4,5,6,7,8,9,10];
$new_array = [];

for ($i = 0; $i < count($array); $i += 5) {
    $new_array = array_merge($new_array, array_slice($array, $i, 3));
}

print_r($new_array);

but lots of calls to array_merge probably isn't the most performant method for large arrays.

avy
  • 644
  • 6
  • 16
0

Hey I have another solution which is not using array_merge which according to @avy solution isn't most performant method for large arrays. I am not using any extra array.

$arr = array(0,1,2,3,4,5,6,7,8,9,10);
$len = sizeOf($arr);
$count = 0;
$i=0;
while($i<$len){
    $count++;
    if($count==3){
            array_splice($arr,$i+1,2);
            $count = 0;
            $len = sizeOf($arr);
    }
    $i++;
 }
print_r($arr);
Samarth
  • 773
  • 1
  • 6
  • 14
  • A quick test of 100k iterations on my machine gives ~360ms for this version vs ~840ms for mine above, so it's definitely worth the extra lines unless the array is known to be small. – avy Apr 03 '17 at 17:06
  • Actually, I take that back (sorry!). For a test with an array of 100k entries run once only, this method takes 17.6s while my version runs in 6.9s. This is faster for lots of small arrays, while mine is faster for one large array. I'll stop posting benchmarks nobody asked for now :) – avy Apr 03 '17 at 21:14
  • Thanks for this version as well! The array is always less than 35 elements big, so size isn't an issue – BusinessGuy Apr 04 '17 at 17:23
  • @avy How are you benchmarking the codes..? I ran the benchmarks by measuring time on both the methods for 100k entries in array. With my version of code time taken was 27137 ms ie ~27.137s and for the same array size your version took 83899ms i.e ~83.89s. And with 10k entries also my version was faster with ~167ms compared to ~375ms of yours. – Samarth Apr 04 '17 at 17:31
  • Replacing `$arr` with `range(0, 100000)` at the top, saving the time in ms just after that, then again at the end. I'm consisently getting a much faster time with my code for arrays > 10k entries (but higher memory usage). I assumed looping in jumps of 5 was saving on operations overall (not that I actually counted the operations). What PHP version are you running? IIRC array operations are much more efficient in 7.x. – avy Apr 04 '17 at 21:51
  • I am using PHP 5.6.28. – Samarth Apr 05 '17 at 07:43