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.
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.
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.