Skip to content
Advertisement

Remove every 3rd and 4th element from array in php

I have below array, i want to skip first 3 element from array (key – 0, 1, 2) and remove next 2 element(key – 3, 4). i.e – I want array like that, it skips every 1st 3 element and remove next 2 element after first 3. I tried below code, but it’s not proper solution for that.

JavaScript

Input array

JavaScript

Advertisement

Answer

You can use array_filter, using the ARRAY_FILTER_USE_KEY flag to pass the element keys to the filter function, and remove all entries whose key % 5 is not < 3:

JavaScript

Output:

JavaScript

Note that if you want the array values 0-indexed, you can pass the result through array_values:

JavaScript

Output:

JavaScript

Demo on 3v4l.org

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement