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!
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.
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);