PHP
Extracting a Column from an Array of Associative Arrays
Learn how to efficiently extract a specific column from an array of associative arrays, transforming it into a simple indexed array using `array_column`.
<?php
$records = [
['id' => 1, 'name' => 'Alice', 'score' => 85],
['id' => 2, 'name' => 'Bob', 'score' => 92],
['id' => 3, 'name' => 'Charlie', 'score' => 78],
];
// Extract 'name' column into an indexed array
$names = array_column($records, 'name');
echo "Names: ";
print_r($names);
/* Output:
Names: Array
(
[0] => Alice
[1] => Bob
[2] => Charlie
)
*/
// Extract 'name' column and use 'id' as keys for the resulting array
$usersById = array_column($records, 'name', 'id');
echo "Names by ID: ";
print_r($usersById);
/* Output:
Names by ID: Array
(
[1] => Alice
[2] => Bob
[3] => Charlie
)
*/
// Re-index the entire array of records by 'id'
$recordsIndexedById = array_column($records, null, 'id');
echo "Records Indexed by ID: ";
print_r($recordsIndexedById);
/* Output:
Records Indexed by ID: Array
(
[1] => Array
(
[id] => 1
[name] => Alice
[score] => 85
)
[2] => Array
(
[id] => 2
[name] => Bob
[score] => 92
)
[3] => Array
(
[id] => 3
[name] => Charlie
[score] => 78
)
)
*/
?>
How it works: The `array_column()` function is a powerful way to retrieve all the values for a single key from a list of associative arrays, transforming them into a simple indexed array. It can also be used to re-index the resulting array by another specified key, or even re-index the original array of arrays, making common data manipulation tasks simpler and more efficient for generating lists or lookups.