Current Location: Home> Latest Articles> Use array_filter() to improve the functional style of the code

Use array_filter() to improve the functional style of the code

M66 2025-06-03

In PHP, although it is not a purely functional programming language, through some built-in functional tools, we can still write more elegant, simpler, and easier to maintain code. array_filter() is such a often overlooked but very powerful tool function. This article will introduce how to use array_filter() to improve your PHP code style and move closer to functional programming.

What is array_filter() ?

array_filter() is one of the built-in array processing functions in PHP, which is used to filter elements in an array. It accepts a callback function that executes the function on each element of the array, and elements with the return value of true will be retained, and others will be removed.

The syntax is as follows:

 array_filter(array $array, ?callable $callback = null, int $mode = 0): array

If no callback function is provided, it will remove values ​​equivalent to false in the array (such as 0 , '' , null , false , etc.).

Usage 1: Clean up the "null value" in the data

Many times we will receive some data from the form or API, which may contain invalid content such as empty strings, null, false, etc. Use array_filter() to clean up a line of code.

 $data = [
    'username' => 'alice',
    'email' => '',
    'age' => null,
    'subscribe' => false,
];

$cleaned = array_filter($data);

print_r($cleaned);

Output:

 Array
(
    [username] => alice
)

This is much more elegant than writing foreach cleanup manually.

Usage 2: Combining anonymous functions for conditional filtering

You can implement more flexible condition filtering by passing in callback functions. For example, filter out active users from a group of users:

 $users = [
    ['name' => 'Alice', 'active' => true],
    ['name' => 'Bob', 'active' => false],
    ['name' => 'Carol', 'active' => true],
];

$activeUsers = array_filter($users, function ($user) {
    return $user['active'];
});

print_r($activeUsers);

The output will contain only Alice and Carol.

Usage 3: Process API response or database results

Suppose you get a set of data from a remote API (such as https://api.m66.net/users ) that contains many invalid or temporary users, you can quickly filter them out:

 $response = file_get_contents('https://api.m66.net/users');
$users = json_decode($response, true);

$validUsers = array_filter($users, function ($user) {
    return isset($user['email']) && filter_var($user['email'], FILTER_VALIDATE_EMAIL);
});

As you can see, array_filter() makes the code closer to the "declarative programming" style, and the code's intentions are clearer, rather than focusing on "how to implement loops and conditions".

Usage 4: Use with other functional methods

You can combine array_filter() with functional methods such as array_map() and array_reduce() to write logical code that has almost no foreach . For example, filter and extract the username of the active user:

 $usernames = array_map(
    fn($user) => $user['name'],
    array_filter($users, fn($user) => $user['active'])
);

Concise and elegant, with clear semantics.

Summarize

array_filter() is a lightweight, powerful and easy to use function. If used well, it can make your PHP more functional and readable. Compared with traditional foreach , it can clearly express the intent in one line of code, reduce boilerplate code, and improve maintainability.

Try to use array_filter() in your next project to improve the quality and style of your code!