Worldscope

PHP array_filter() Function

Palavras-chave:

Publicado em: 05/08/2025

Understanding the PHP array_filter() Function

The array_filter() function in PHP is a powerful tool for selectively extracting elements from an array based on a user-defined criteria. This article provides a comprehensive guide to using array_filter(), covering its syntax, usage, and performance considerations. We'll delve into practical examples, explain the underlying logic, and compare it with alternative methods.

Fundamental Concepts / Prerequisites

To effectively understand array_filter(), you should be familiar with the following PHP concepts:

  • Arrays: Understanding how to declare, access, and iterate through arrays.
  • Functions: Knowing how to define and use custom functions in PHP.
  • Callbacks: Grasping the concept of passing functions as arguments to other functions (callbacks).
  • Boolean logic: Understanding how boolean conditions (true/false) work.

Core Implementation/Solution

The array_filter() function takes an array and an optional callback function as arguments. It returns a new array containing only the elements from the original array that satisfy the condition defined in the callback function. If no callback is provided, it will remove all entries of array that equal false (see converting to boolean for more information). This means that, if no callback is provided, all entries of array with a value equal to false will be removed.


<?php

/**
 * Example demonstrating the use of array_filter() with a custom callback.
 *
 * @param array $numbers An array of numbers.
 * @return array A new array containing only the even numbers from the input array.
 */
function getEvenNumbers(array $numbers): array
{
    // Define a callback function to check if a number is even.
    $isEven = function ($number) {
        return $number % 2 === 0;
    };

    // Use array_filter() to filter the array, keeping only even numbers.
    $evenNumbers = array_filter($numbers, $isEven);

    return $evenNumbers;
}

// Example usage
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$evenNumbers = getEvenNumbers($numbers);

// Print the resulting array
print_r($evenNumbers);

// Example usage with no callback (removing empty and falsey values)
$data = [0, 1, false, 2, '', 3, null, 4];
$filteredData = array_filter($data);
print_r($filteredData);

?>

Code Explanation

The code above demonstrates how to use array_filter() in PHP. Let's break it down:

1. **`getEvenNumbers(array $numbers): array` function:** This function takes an array of numbers as input and returns a new array containing only the even numbers.

2. **`$isEven = function ($number) { ... }`:** An anonymous function (also known as a closure) is defined and assigned to the `$isEven` variable. This function takes a single number as input and returns `true` if the number is even (i.e., divisible by 2), and `false` otherwise. This is the callback function that will be used by array_filter().

3. **`$evenNumbers = array_filter($numbers, $isEven);`:** This is the core of the example. array_filter() is called with two arguments: the `$numbers` array and the `$isEven` callback function. array_filter() iterates through each element of the `$numbers` array, passing each element to the `$isEven` function. If `$isEven` returns `true` for a particular element, that element is included in the resulting `$evenNumbers` array. Otherwise, the element is skipped.

4. **`print_r($evenNumbers);`:** This line prints the resulting `$evenNumbers` array, which will contain only the even numbers from the original `$numbers` array.

5. **Example with no callback:** This demonstrates how array_filter() behaves when no callback function is provided. In this case, it removes all elements from the array that evaluate to `false` in a boolean context. This includes `0`, `false`, `''` (empty string), and `null`. Note that `"0"` and other strings that contain something will pass the filter.

Complexity Analysis

The array_filter() function iterates through each element of the input array. Therefore, the time complexity is **O(n)**, where n is the number of elements in the array.

The space complexity is also **O(n)** in the worst-case scenario. This occurs when all elements in the original array satisfy the condition defined in the callback function, resulting in a new array with the same size as the original array. In the best case, if no elements satisfy the condition, the space complexity would be O(1) since only a small empty array would be created. The space usage depends directly on the filter and original data.

Alternative Approaches

One alternative approach to achieve the same result as array_filter() is to use a `foreach` loop. You would iterate through the original array, check each element against your condition, and manually add the element to a new array if it meets the criteria.


<?php

$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
$evenNumbers = [];

foreach ($numbers as $number) {
    if ($number % 2 === 0) {
        $evenNumbers[] = $number;
    }
}

print_r($evenNumbers);

?>

While a `foreach` loop offers more fine-grained control, array_filter() is generally more concise and readable, especially for simple filtering tasks. The performance differences are often negligible for smaller arrays, but array_filter() can potentially be more efficient for larger arrays due to its internal optimizations.

Conclusion

The array_filter() function provides a convenient and efficient way to filter arrays in PHP based on a custom criteria. Understanding its syntax, usage, and performance characteristics allows developers to write cleaner and more maintainable code. By leveraging callback functions, you can easily tailor the filtering logic to meet specific requirements. While alternative approaches like `foreach` loops exist, array_filter() often offers a more concise and performant solution.