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.
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']
];
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.
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";
}
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.