PHP
Extracting a Column from a PHP Array of Arrays
Quickly retrieve all values from a specific column across an array of associative arrays in PHP using `array_column`, ideal for lists of records like user data or product information.
<?php
$records = [
['id' => 101, 'name' => 'Alice', 'email' => '[email protected]'],
['id' => 102, 'name' => 'Bob', 'email' => '[email protected]'],
['id' => 103, 'name' => 'Charlie', 'email' => '[email protected]'],
['id' => 104, 'name' => 'David', 'email' => '[email protected]']
];
// Extract all 'name' values
$names = array_column($records, 'name');
print_r($names);
// Extract all 'id' values
$ids = array_column($records, 'id');
print_r($ids);
// Extract 'name' values, using 'id' as the keys of the new array
$namesById = array_column($records, 'name', 'id');
print_r($namesById);
?>
How it works: The `array_column()` function returns the values from a single column in the input array. It's particularly useful when working with an array of associative arrays (like database query results) where you need to extract all values for a specific key. The optional third argument allows you to specify a column whose values will be used as the keys for the output array, providing a convenient way to create keyed lookups.