In PHP, we often need to deal with multidimensional arrays, especially when filtering out specific rows from arrays. PHP provides many practical functions to help us perform these operations efficiently, among which array_column and array_intersect are two very commonly used functions.
The array_column function can be used to obtain the value of a specified column in a multidimensional array, while the array_intersect function can be used to find the part of an array that intersects with another array. Combining these two functions, we can easily filter out rows containing specific values. This article will use a simple example to show how to use these two functions for filtering.
Suppose we have a multidimensional array containing multiple user information, each user information is an associative array. We need to filter out all user information with email address example@m66.net . You can use array_column to get all email addresses, and then use array_intersect to find lines containing specific email addresses.
<?php
// User data
$users = [
['id' => 1, 'name' => 'Alice', 'email' => 'alice@m66.net'],
['id' => 2, 'name' => 'Bob', 'email' => 'bob@m66.net'],
['id' => 3, 'name' => 'Charlie', 'email' => 'charlie@m66.net'],
['id' => 4, 'name' => 'David', 'email' => 'example@m66.net'],
['id' => 5, 'name' => 'Eve', 'email' => 'eve@m66.net'],
];
// Specific email addresses that need to be filtered
$targetEmail = 'example@m66.net';
// use array_column Get all email addresses
$emails = array_column($users, 'email');
// use array_intersect Find the same row as the target mailbox
$filteredUsers = array_filter($users, function ($user) use ($emails, $targetEmail) {
return in_array($targetEmail, $emails) && $user['email'] === $targetEmail;
});
// Output filter results
print_r($filteredUsers);
?>
array_column : This function is used to extract the specified column from a multidimensional array. Here we use array_column($users, 'email') to extract all users' email addresses and store them in the $emails array.
array_intersect : This function can return the intersection between arrays. In this example, we do not use array_intersect directly to compare array intersections, but use in_array to check whether the email address exists in the target array. If a matching email address is found, we return the corresponding line.
array_filter : Used to filter arrays and filter out elements that meet the criteria. In this example, we filter out the rows with the email address 'example@m66.net' through a custom callback function.
When running the above code, the $filteredUsers array will only contain user data with the mailbox 'example@m66.net' , and the output result is as follows: