// ------------------------------------------------------------
// A small program demonstrating how to remove every Nth element
// from an array using clear, expressive PHP patterns.
// ------------------------------------------------------------
/*
This function returns a new array with every Nth element removed.
It performs a single pass over the input array. PHP arrays are
zero‑based when accessed by index, so we check ($index + 1) % $n !== 0
to keep elements that are *not* in the Nth position.
The variable $size captures the array length before the loop,
which avoids repeatedly calling count($items) inside the loop.
*/
function removeEveryNth(array $items, int $n): array
{
if ($n <= 0) {
throw new InvalidArgumentException("n must be a positive integer");
}
$size = count($items); // capture size once
$result = []; // output array
for ($i = 0; $i < $size; $i++) {
if (($i + 1) % $n !== 0) {
$result[] = $items[$i];
}
}
return $result;
}
/*
Keeping the main execution block small and focused makes the program
easy to extend. Here we demonstrate the function with a simple example.
*/
$data = range(1, 20); // Example list: numbers 1–20
$n = 3; // Remove every 3rd element
$cleaned = removeEveryNth($data, $n);
echo "Original: " . implode(" ", $data) . PHP_EOL;
echo "After removing every {$n}-th element: " . implode(" ", $cleaned) . PHP_EOL;
/*
run:
Original: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
After removing every 3-th element: 1 2 4 5 7 8 10 11 13 14 16 17 19 20
*/