Current Location: Home> Latest Articles> array_filter() is used in combination with anonymous functions

array_filter() is used in combination with anonymous functions

M66 2025-06-05

Filtering array data in PHP is a very common operation, especially when processing user input, API data, or database results. array_filter() is a powerful function provided by PHP, which can combine anonymous functions (closures) to achieve flexible and efficient data filtering. This article will take you step by step to understand how to use them to implement various filtering logic.

1. What is array_filter() ?

array_filter() is a built-in PHP function that judges each element in the array through a callback function (callback) and returns a new array composed of elements that meet the conditions.

The basic syntax is as follows:

 array_filter(array $array, ?callable $callback = null, int $mode = 0): array
  • $array : The array to filter.

  • $callback : The callback function used for each element. If omitted, elements with a value of false will be removed by default.

  • $mode : Optional parameter to determine whether to pass the key name as a parameter.

2. Introduction to anonymous functions and closures

Anonymous functions, also known as closures, are a function without a name in PHP, which is very suitable for use during temporary logic processing. The syntax is as follows:

 $filterFunc = function($value) {
    return $value > 10;
};

This type of function is usually used with array_filter() to achieve more granular data control.

3. Combination use examples

Example 1: Filter numbers greater than 10

 $numbers = [4, 15, 9, 23, 5];

$filtered = array_filter($numbers, function($value) {
    return $value > 10;
});

print_r($filtered);

Output:

 Array
(
    [1] => 15
    [3] => 23
)

You can see that only numbers greater than 10 are retained.

Example 2: Filter empty fields in an array (for example after form is submitted)

 $formData = [
    'name' => 'Alice',
    'email' => '',
    'age' => null,
    'city' => 'Beijing'
];

$cleanData = array_filter($formData, function($value) {
    return !empty($value);
});

print_r($cleanData);

Output:

 Array
(
    [name] => Alice
    [city] => Beijing
)

Example 3: Keep elements whose key names contain specific strings in the key value pair

 $data = [
    'user_id' => 101,
    'user_name' => 'Bob',
    'admin_role' => true,
    'timestamp' => 1681920000
];

$filtered = array_filter($data, function($value, $key) {
    return str_contains($key, 'user');
}, ARRAY_FILTER_USE_BOTH);

print_r($filtered);

Output:

 Array
(
    [user_id] => 101
    [user_name] => Bob
)

Example 4: Filtering with URL data

Suppose you get the following array from a data source (such as https://m66.net/api/posts ):

 $posts = [
    ['title' => 'Hello World', 'url' => 'https://m66.net/post/1', 'published' => true],
    ['title' => 'Draft Post', 'url' => 'https://m66.net/post/2', 'published' => false],
    ['title' => 'PHP Tips', 'url' => 'https://m66.net/post/3', 'published' => true],
];

You can use array_filter() to keep only published articles:

 $publishedPosts = array_filter($posts, function($post) {
    return $post['published'] === true;
});

print_r($publishedPosts);

4. Summary

Using array_filter() combined with anonymous functions can easily achieve various customized data filtering needs. Whether it is filtering numeric values, strings or multi-dimensional arrays, you only need to pass in a suitable closure function to handle it flexibly.

suggestion:

  • When processing user data, be sure to use filters to clear unwanted content.

  • Use anonymous functions to improve code readability and modularity as much as possible.

  • If you want to keep the key name consistent with the original array, you can use it with ARRAY_FILTER_USE_BOTH .