Filter Even Numbers
Write a PHP function that takes an array of integers and returns only the even numbers from the array. Use array_filter() with a callback function that checks if each element is even.
The array_filter() function iterates through the array and applies the callback to each element. If the callback returns true, the element is included in the result. The modulo operator % checks divisibility: $n % 2 === 0 means the number is even.
Edge cases include empty arrays (return []), arrays with no even numbers (return []), and negative even numbers. The callback should preserve array keys by default.
The array_filter() function with a callback is a common PHP pattern for filtering arrays. The callback should return true to keep the element. Using array_values() reindexes the result to start from 0, which is often expected for output.
Filtering arrays with callbacks is a functional programming concept available in PHP through array_filter(), array_map(), and array_reduce(). These functions operate on arrays without explicit loops, leading to more declarative and readable code.
The callback function passed to array_filter() receives each element's value and key. Returning true includes the element in the result. The array_values() function reindexes the filtered array from 0, which is important when the result needs sequential numeric keys.
Example Input & Output
Algorithm Flow

Solution Approach
Use array_filter($nums, function($n) { return $n % 2 === 0; }). The callback returns true for even numbers, false for odd numbers. array_filter() returns only the elements where the callback returns true.
For a manual loop approach: initialize an empty result array, use foreach to iterate, check each element with $n % 2 === 0, and add matches to the result array.
Edge cases include empty input (returns empty array), all odd numbers (returns empty array), and negative even numbers (correctly identified).
The time complexity is O(n). Space complexity is O(n) for the result array.
Best Answers
<?php
function filterEvens($nums) {
return array_values(array_filter($nums, function($n) { return $n % 2 === 0; }));
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
