Home >Backend Development >PHP Tutorial >How to quickly filter array data using PHP arrow functions
How to use PHP arrow functions to quickly filter array data
Introduction:
The arrow function feature was introduced in PHP 7.4 version, which makes the code Write more concisely and quickly. This article will introduce how to use arrow functions to quickly filter array data and provide specific code examples.
Step 1: Create an array for demonstration
First, we need to create an array for demonstration. The following is a sample array:
$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'] ];
Step 2: Filter the array data
Next, define a callback function in the arrow function to filter the array data. Here is an example of using arrow functions to filter an array:
$filteredUsers = array_filter($users, fn($user) => $user['age'] > 25);
In the above example, the array_filter
function is used to filter the data in the array $users
. Arrow function fn($user) => $user['age'] > 25
acts as a callback function on each array element, returning users whose age is greater than 25.
Step 3: Print the filtered results
Finally, we can print out the filtered results. The following is an example:
foreach($filteredUsers as $user) { echo "Name: " . $user['name'] . ", Age: " . $user['age'] . ", Country: " . $user['country'] . " "; }
In the above example, use foreach
to loop through the filtered user array and print the name, age, and country of each user.
Full code example:
$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'] ]; $filteredUsers = array_filter($users, fn($user) => $user['age'] > 25); foreach($filteredUsers as $user) { echo "Name: " . $user['name'] . ", Age: " . $user['age'] . ", Country: " . $user['country'] . " "; }
Conclusion:
Use PHP arrow functions to filter array data quickly and concisely. By defining a callback function as an arrow function, we can easily filter the array if specific conditions are met. This feature improves code readability and writing efficiency.
Tip: Please make sure your PHP version is 7.4 or higher for arrow functions to run correctly.
The above is the detailed content of How to quickly filter array data using PHP arrow functions. For more information, please follow other related articles on the PHP Chinese website!