Current Location: Home> Latest Articles> Practical Tips for Quickly Filtering Arrays Using PHP Arrow Functions

Practical Tips for Quickly Filtering Arrays Using PHP Arrow Functions

M66 2025-08-02

Introduction to Quickly Filtering Arrays with PHP Arrow Functions

PHP 7.4 introduced arrow functions, which make code more concise and readable. This article demonstrates how to use arrow functions to quickly filter data within arrays, helping you handle array operations more efficiently.

Creating the Sample Array

First, define an array containing multiple user information entries for demonstration purposes:

$users = [
    ['name' => 'John', 'age' => 25, 'country' => 'USA'],
    ['name' => 'Alice', 'age' => 30, 'country' => 'Canada'],
    ['name' => 'Bob', 'age' => 20, 'country' => 'Australia'],
    ['name' => 'Mike', 'age' => 35, 'country' => 'USA']
];

Filtering the Array Using Arrow Functions

Next, use array_filter along with an arrow function to quickly select users older than 25:

$filteredUsers = array_filter($users, fn($user) => $user['age'] > 25);

Here, the arrow function fn($user) => $user['age'] > 25 acts as a callback to check if each element meets the condition.

Displaying the Filtered Results

Use a foreach loop to iterate over the filtered array and print each user's name, age, and country:

foreach ($filteredUsers as $user) {
    echo "Name: " . $user['name'] . ", Age: " . $user['age'] . ", Country: " . $user['country'] . "\n";
}

Conclusion

PHP arrow functions not only simplify syntax but greatly enhance the efficiency and readability of array filtering and similar operations. Complex filtering logic can be achieved with just one line of code, making it highly recommended for PHP 7.4 and above.

Make sure your environment supports arrow functions to ensure smooth execution of the code.