Current Location: Home> Latest Articles> Extract all email addresses in user array

Extract all email addresses in user array

M66 2025-05-11

In PHP, when processing arrays, it is often necessary to extract specific fields from complex multi-dimensional arrays. The array_column function is a very useful tool that can easily extract the value of a column from a multidimensional array. This article will teach you how to use the array_column function to extract all email addresses from a user array.

1. Basic usage

The basic usage of the array_column function is to extract a column of data from a multi-dimensional array. Its function signature is as follows:

 array_column(array $input, mixed $column_key, mixed $index_key = null): array
  • $input : The multi-dimensional array of input.

  • $column_key : The key name of the column we need to extract.

  • $index_key : If specified, the resulting array will be indexed by pressing this key.

2. Example: Extract email address

Suppose we have an array of user information, each user contains multiple fields, including email address, username, etc. We want to extract all email addresses from this array.

 <?php
// User information array
$users = [
    ['id' => 1, 'name' => 'John Doe', 'email' => 'john.doe@m66.net'],
    ['id' => 2, 'name' => 'Jane Smith', 'email' => 'jane.smith@m66.net'],
    ['id' => 3, 'name' => 'Alice Johnson', 'email' => 'alice.johnson@m66.net'],
    ['id' => 4, 'name' => 'Bob Brown', 'email' => 'bob.brown@m66.net']
];

// usearray_columnExtract email address
$emails = array_column($users, 'email');

// Output email address
print_r($emails);
?>

3. Code explanation

  • The $users array contains information about multiple users, each user is an associative array containing id , name and email fields.

  • Using array_column($users, 'email') we extract all email columns from the $users array.

  • Finally, print_r($emails) to print out the extracted mailbox address array.

After running the code, the output will be:

 Array
(
    [0] => john.doe@m66.net
    [1] => jane.smith@m66.net
    [2] => alice.johnson@m66.net
    [3] => bob.brown@m66.net
)

4. Extract the email address and re-release

Sometimes, we may have duplicate email addresses in our array. If you want to deduplicate, you can use the array_unique function:

 <?php
// Email address after deduplication
$uniqueEmails = array_unique($emails);

// 输出Email address after deduplication
print_r($uniqueEmails);
?>

5. Summary

The array_column function is a very convenient tool for extracting specific column data from a multidimensional array. When extracting email addresses, you only need to pass in the key names of the array and email addresses, and it can quickly return the list of all email addresses.

This method is very suitable for processing user data, order information and other scenarios, and can greatly simplify code and improve efficiency.