PHP
Extract a Column from an Array of Associative Arrays
Discover how to easily extract a specific column from an array of associative arrays using PHP's `array_column()`. Perfect for getting lists of IDs, names, or other properties from structured data.
<?php
$records = [
['id' => 101, 'name' => 'Alice', 'score' => 85],
['id' => 102, 'name' => 'Bob', 'score' => 92],
['id' => 103, 'name' => 'Charlie', 'score' => 78],
['id' => 104, 'name' => 'Alice', 'score' => 95]
];
// Get all 'name' values
$names = array_column($records, 'name');
print_r($names);
// Expected Output: Array ( [0] => Alice [1] => Bob [2] => Charlie [3] => Alice )
// Get 'score' values, using 'id' as keys
$scoresById = array_column($records, 'score', 'id');
print_r($scoresById);
// Expected Output: Array ( [101] => 85 [102] => 92 [103] => 78 [104] => 95 )
?>
How it works: The `array_column()` function provides a convenient way to extract the values of a single column (or key) from an array of associative arrays. It can also be used to index the resulting array by the values of another specified column, making it incredibly powerful for transforming data structures, such as fetching a list of user IDs or product names from a database result set or API response.