Sometimes we want to keep only every other element in an array, and place those elements in another array. Other distances, like every 3 elements, can also be used.
With PHP it is possible to develop a function that performs this task. We can use modulo division to determine whether an element at index is supposed to be retained.
Here we introduce the every_nth_element()
function. It creates a new array that is populated in the foreach
loop, and then returned at the end.
foreach
-loop over the keys in the array by calling array_keys
. This gives us the indexes of each array element.foreach
-loop. This array then can be used when every_nth_element
is called.function every_nth_element($array, $n) { $result = []; // Step 1: Loop over array keys (indexes of the array). foreach (array_keys($array) as $i) { // Step 2: If the index is evenly divisible by the argument, add it to the array. if ($i % $n == 0) { $result[] = $array[$i]; } } // Step 3: Return the array we built up. return $result; } // Use the function on this array. $letters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]; $result = every_nth_element($letters, 2); print_r($result); $result = every_nth_element($letters, 3); print_r($result);Array ( [0] => a [1] => c [2] => e [3] => g [4] => i ) Array ( [0] => a [1] => d [2] => g )
It is easy to see that when the argument to every_nth_element
is 2, we keep every other element in the letters array. With an argument of 3, we skip over 2 letters after each letter.
With a foreach
-loop, we can avoid using an error-prone for
-loop for our PHP functions. By appending to a new array, we can build up the result array.