PHP
Extract a Specific Column from an Array of Associative Arrays
Learn to efficiently extract a single column of values from an array of associative arrays in PHP using the array_column function for focused data transformation.
<?php
$records = [
['id' => 101, 'first_name' => 'Alice', 'last_name' => 'Smith'],
['id' => 102, 'first_name' => 'Bob', 'last_name' => 'Johnson'],
['id' => 103, 'first_name' => 'Charlie', 'last_name' => 'Brown']
];
// Extract just the 'first_name' column
$firstNames = array_column($records, 'first_name');
print_r($firstNames);
/* Output:
Array
(
[0] => Alice
[1] => Bob
[2] => Charlie
)
*/
// Extract 'first_name' and use 'id' as keys
$firstNamesById = array_column($records, 'first_name', 'id');
print_r($firstNamesById);
/* Output:
Array
(
[101] => Alice
[102] => Bob
[103] => Charlie
)
*/
How it works: The `array_column()` function in PHP allows you to easily extract a single column from a multi-dimensional array or an array of objects. It takes the input array, the column name or index to return, and an optional third parameter for the column to use as the keys for the returned array. This is extremely useful for generating lists, creating dropdown options, or preparing data for other operations without complex loops.