Home
PHP
array Every Nth Element
This page was last reviewed on Aug 3, 2023.
Dot Net Perls
Nth element. 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.
function
Example. 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.
Step 1 We use a foreach-loop over the keys in the array by calling array_keys. This gives us the indexes of each array element.
foreach
Step 2 We use modulo division based on the "n" argument to determine if the current element is in an index where we keep the element.
Step 3 We return the array we built up in the foreach-loop. This array then can be used when every_nth_element is called.
array
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 )
Results. 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.
Summary. 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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Aug 3, 2023 (new).
Home
Changes
© 2007-2024 Sam Allen.