Code Logo

Filter Even Numbers

Published at24 Jul 2026
PHP Data Structures Easy 0 views
Like0

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

Example 1
Input
[]
Output
[]
Example 2
Input
[2]
Output
[2]
Example 3
Input
[1,2,3,4,5,6]
Output
[2,4,6]
Example 4
Input
[1,3,5]
Output
[]
Example 5
Input
[-2,-3,-4]
Output
[-2,-4]

Algorithm Flow

Recommendation Algorithm Flow for Filter Even Numbers
Recommendation Algorithm Flow for Filter Even Numbers

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 - Approach 1
<?php
function filterEvens($nums) {
    return array_values(array_filter($nums, function($n) { return $n % 2 === 0; }));
}