← Back to all snippets
PHP

Extract Column from Array of Associative Arrays

Discover how to efficiently extract a single column of values from an array of associative arrays, perfect for database results, using PHP's array_column.

$records = [
    ['id' => 101, 'name' => 'Alice', 'score' => 85],
    ['id' => 102, 'name' => 'Bob', 'score' => 92],
    ['id' => 103, 'name' => 'Charlie', 'score' => 78]
];

$ids = array_column($records, 'id');
$names = array_column($records, 'name');

print_r($ids);
// Output: Array
// (
//    [0] => 101
//    [1] => 102
//    [2] => 103
// )
print_r($names);
// Output: Array
// (
//    [0] => Alice
//    [1] => Bob
//    [2] => Charlie
// )
How it works: The `array_column()` function extracts a single column (specified by `column_key`) from an array of arrays (or objects). It's incredibly useful for scenarios where you have a dataset, like results from a database query, and you need to quickly get a flat list of specific values, such as all user IDs or product names.

Need help integrating this into your project?

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

Hire DigitalCodeLabs