Filter array by skipping every nth element from the end



PHP Snippet 1:

function skipFromBack(array $array, int $skip): array {
    $result = [];
    for ($index = array_key_last($array); $index > -1; $index -= 1 + $skip) {
        $result[] = $array[$index];
    }
    return array_reverse($result);
}

PHP Snippet 2:

function skipFromBack(array $array, int $skip): array {
    $increment = $skip + 1;
    $count = count($array);
    $start = ($count - 1) % $increment;
    $result = [];
    for ($i = $start; $i < $count; $i += $increment) {
        $result[] = $array[$i];
    }
    return $result;
}

PHP Snippet 3:

function skip_x_elements($array, $x)
{
    $newArray = [];
    $skipCount = 0;
    foreach ($array as $value) {
        if ($skipCount === $x) {
            $newArray[] = $value;
            $skipCount = 0;
        } else {
            $skipCount++;
        }
    }
    return $newArray;
}

PHP Snippet 4:

function skipX($array, $x, $grab = false){
    $x = (!$grab) ? $x: $x - 1;
    if($x <= 0) return $array;
    $count = (count($array) % $x == 0) ? 0:$x;
    $temparr = [];
    foreach($array as $key => $value){
        if($count === $x){
            $temparr[$key] = $value;
            $count = 0;
        }else $count++;
    }
    return $temparr;
}

PHP Snippet 5:

$array = range(0, 15);
foreach ([0, 1, 2, 3] as $skip){
    print_r(skipX($array, $skip));
    echo "\n---\n";
}

PHP Snippet 6:

Array
(
    [0] => 0
    [1] => 1
    [2] => 2
    [3] => 3
    [4] => 4
    [5] => 5
    [6] => 6
    [7] => 7
    [8] => 8
    [9] => 9
    [10] => 10
    [11] => 11
    [12] => 12
    [13] => 13
    [14] => 14
    [15] => 15
)

---
Array
(
    [1] => 1
    [3] => 3
    [5] => 5
    [7] => 7
    [9] => 9
    [11] => 11
    [13] => 13
    [15] => 15
)

---
Array
(
    [2] => 2
    [5] => 5
    [8] => 8
    [11] => 11
    [14] => 14
)

---
Array
(
    [0] => 0
    [4] => 4
    [8] => 8
    [12] => 12
)

---