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.

for($i = 0; $i < count($newArray); $i += 1) {
    if($i == 3 || $i == 4 || $i == 8 || $i == 9){
        unset($newArray[$i]);
    }
}

Input array

Array
    (
        [0] => 0.393
        [1] => 0.769
        [2] => 0.189
        [3] => 0
        [4] => 0
        [5] => 0.349
        [6] => 0.686
        [7] => 0.168
        [8] => 0
        [9] => 0
        [10] => 0.272
        [11] => 0.534
        [12] => 0.131
        [13] => 1
        [14] => 0
    )

**Expected Output**

    Array
            (
                [0] => 0.393
                [1] => 0.769
                [2] => 0.189
                [3] => 0.349
                [4] => 0.686
                [5] => 0.168
                [6] => 0.272
                [7] => 0.534
                [8] => 0.131
            )

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:

$newArray = array_filter($newArray, function ($k) { return $k % 5 < 3; }, ARRAY_FILTER_USE_KEY );
print_r($newArray);

Output:

Array
(
    [0] => 0.393
    [1] => 0.769
    [2] => 0.189
    [5] => 0.349
    [6] => 0.686
    [7] => 0.168
    [10] => 0.272
    [11] => 0.534
    [12] => 0.131
)

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

$newArray = array_values($newArray);
print_r($newArray);

Output:

Array
(
    [0] => 0.393
    [1] => 0.769
    [2] => 0.189
    [3] => 0.349
    [4] => 0.686
    [5] => 0.168
    [6] => 0.272
    [7] => 0.534
    [8] => 0.131
)

Demo on 3v4l.org

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