PHP
Extracting a Single Column from a Multi-dimensional Array
Learn to easily extract all values for a specific key from an array of associative arrays, generating a new simple indexed array of those values in PHP.
<?php
$records = [
['id' => 101, 'name' => 'John Doe', 'email' => '[email protected]'],
['id' => 102, 'name' => 'Jane Smith', 'email' => '[email protected]'],
['id' => 103, 'name' => 'Peter Jones', 'email' => '[email protected]']
];
// Extract all 'name' values
$names = array_column($records, 'name');
print_r($names);
// Output: Array ( [0] => John Doe [1] => Jane Smith [2] => Peter Jones )
// Extract 'email' values, indexed by 'id'
$emailsById = array_column($records, 'email', 'id');
print_r($emailsById);
/* Output:
Array
(
[101] => [email protected]
[102] => [email protected]
[103] => [email protected]
)
*/
?>
How it works: The `array_column()` function returns the values from a single column in the input array. It's incredibly useful for quickly extracting specific data from a list of records (e.g., from a database result set or a CSV import) into a simple, one-dimensional array. Optionally, you can specify a `key_column` to use the values from that column as the keys for the output array, creating a convenient lookup table.