PHP

Extract a Specific Column from Multi-dimensional Arrays

Efficiently pull out values from a single key across an array of arrays or objects into a simple list using PHP's built-in array_column function.

<?php
$records = [
    ['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
    ['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
    ['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]'],
];

// Extract all 'name' values
$names = array_column($records, 'name');
print_r($names);
/*
Output:
Array
(
    [0] => Alice
    [1] => Bob
    [2] => Charlie
)
*/

// Extract 'email' values, using 'id' as keys for the new array
$emails_by_id = array_column($records, 'email', 'id');
print_r($emails_by_id);
/*
Output:
Array
(
    [1] => [email protected]
    [2] => [email protected]
    [3] => [email protected]
)
*/
How it works: The `array_column()` function is a powerful tool for extracting values from a single 'column' (a specific key) in a multi-dimensional array or an array of objects. It returns an indexed array containing all values for the specified key. Optionally, you can provide a third argument to use the values of another key from the input arrays 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