PHP
Extract a Column from an Array of Objects/Arrays
Learn how to easily extract a single column of values from an array of associative arrays or objects in PHP using `array_column` for cleaner data processing.
<?php
$records = [
['id' => 1, 'name' => 'Alice', 'age' => 30],
['id' => 2, 'name' => 'Bob', 'age' => 24],
['id' => 3, 'name' => 'Charlie', 'age' => 35],
];
$names = array_column($records, 'name');
print_r($names);
// Expected output: Array ( [0] => Alice [1] => Bob [2] => Charlie )
// To use 'id' as keys for the names:
$names_keyed_by_id = array_column($records, 'name', 'id');
print_r($names_keyed_by_id);
// Expected output: Array ( [1] => Alice [2] => Bob [3] => Charlie )
?>
How it works: The `array_column()` function is highly efficient for extracting values from a single column in a multi-dimensional array or an array of objects. You provide the input array, the key/property name for the column to retrieve, and optionally, a key to use for the index of the resulting array. This is extremely useful when dealing with datasets from databases or APIs, allowing you to quickly get a list of specific attributes.