PHP
Extract Specific Column from Array of Associative Arrays
Learn how to easily extract a single column of values from an array of associative arrays in PHP using the `array_column` function for simplified data access.
<?php
function extractColumn(array $data, string $columnName): array
{
return array_column($data, $columnName);
}
$records = [
['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]']
];
$names = extractColumn($records, 'name');
$ids = extractColumn($records, 'id');
print_r($names);
print_r($ids);
// Output for $names:
// Array
// (
// [0] => Alice
// [1] => Bob
// [2] => Charlie
// )
// Output for $ids:
// Array
// (
// [0] => 1
// [1] => 2
// [2] => 3
// )
How it works: The `array_column()` function is incredibly useful for working with arrays of associative arrays, common when dealing with database results or API responses. It allows you to quickly pull all the values for a specific key across all sub-arrays, returning them as a simple indexed array. This simplifies data manipulation and access to specific data points.