PHP

Easily Extract a Column from a PHP Array of Arrays

Use PHP's `array_column` function to quickly pull all values for a specific key from a list of associative arrays or objects, creating a new flat array.

<?php
$users = [
    ['id' => 101, 'first_name' => 'John', 'last_name' => 'Doe', 'email' => '[email protected]'],
    ['id' => 102, 'first_name' => 'Jane', 'last_name' => 'Smith', 'email' => '[email protected]'],
    ['id' => 103, 'first_name' => 'Peter', 'last_name' => 'Jones', 'email' => '[email protected]']
];

// Extract only the 'email' column
$emails = array_column($users, 'email');
print_r($emails);

// Extract 'first_name' and use 'id' as the keys for the new array
$firstNamesById = array_column($users, 'first_name', 'id');
print_r($firstNamesById);

/*
Output:
Array
(
    [0] => [email protected]
    [1] => [email protected]
    [2] => [email protected]
)
Array
(
    [101] => John
    [102] => Jane
    [103] => Peter
)
*/
How it works: The `array_column()` function is a highly efficient way to extract a single column from an array of arrays (or an array of objects). It takes the input array, the key for the column you want to retrieve, and optionally, a key to use as the index for the resulting array. This greatly simplifies tasks like generating lists of specific data points (e.g., all emails) or creating lookup tables from structured data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs