Extract a Single Column From a Multidimensional Array in PHP

Imagine you have an array containing information about several users and you want to extract only a certain value.

See this example.

$users = [
    [
        'id' => 1,
        'name' => 'John',
        'email' => 'john@example.com'
    ],
    [
        'id' => 2,
        'name' => 'Sarah',
        'email' => 'sarah@example.com'
    ],
    [
        'id' => 3,
        'name' => 'Mike',
        'email' => 'mike@example.com'
    ]
];

Now, you want to extract only the email addresses from this multidimensional array.

One way to accomplish this is by using a foreach loop:

$emails = [];

foreach ($users as $user) {
    $emails[] = $user['email'];
}

This works perfectly fine, but PHP offers a much simpler solution.

The Solution: PHP array_column()

The built-in PHP function array_column() allows you to extract values from a specific column of a multidimensional array.

Some common situations where this function can save time are:

  • Extracting email addresses from user records.
  • Getting product names from a product list.
  • Collecting IDs from database query results.
  • Preparing specific data fields for further processing.

Instead of writing a complete loop, you can accomplish the same task with just one line of code:

$emails = array_column($users, 'email');

print_r($emails);

The syntax of the array_column() function is:

array_column(array, column_key, [index_key]);

The three parameters of the function are:

  • array: The input multidimensional array.
  • column_key: The column of values you want to extract.
  • index_key: Optional. The column used as the keys of the resulting array.

The output is:

Array
(
    [0] => john@example.com
    [1] => sarah@example.com
    [2] => mike@example.com
)

That’s it! All email addresses have been extracted into a new array.

array_column() offers a comfortable way to extract certain columns from an array. Of course, you could also solve this by some hand written code loops. But why should you? This PHP function makes coding easy. 😉

(Visited 1 times, 1 visits today)

Leave a Comment