PHP

Extract Specific Column Values from Array of Associative Arrays

Discover how to quickly extract all values for a particular key or property from an array of associative arrays or objects in PHP using the `array_column` function.

$users = [
    ['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
    ['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
    ['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]'],
];

$userNames = array_column($users, 'name');
print_r($userNames);
// Output: Array ( [0] => Alice [1] => Bob [2] => Charlie )

$userIdsAsKeys = array_column($users, 'name', 'id');
print_r($userIdsAsKeys);
// Output: Array ( [1] => Alice [2] => Bob [3] => Charlie )
How it works: The `array_column` function is highly efficient for extracting a specific column (or field) from a list of arrays or objects. It can return a simple indexed array of values. Additionally, you can provide a third argument to use values from another column as the keys in the resulting array, making it perfect for creating lookup tables.

Need help integrating this into your project?

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

Hire DigitalCodeLabs