PHP
Extract Specific Column from Array of Arrays
Easily extract all values from a single column within a multi-dimensional PHP array, creating a simple indexed array of those values for processing.
<?php
$records = [
['id' => 1, 'first_name' => 'John', 'last_name' => 'Doe'],
['id' => 2, 'first_name' => 'Jane', 'last_name' => 'Smith'],
['id' => 3, 'first_name' => 'Peter', 'last_name' => 'Jones']
];
// Extract all 'first_name' values
$firstNames = array_column($records, 'first_name');
print_r($firstNames);
// Extract 'id' values, using 'first_name' as keys
$idByFirstName = array_column($records, 'id', 'first_name');
print_r($idByFirstName);
?>
How it works: The `array_column()` function provides a convenient way to extract a single column from a multi-dimensional array or an array of objects. It takes the input array, the key/column to return, and optionally, a key/column to use as the index for the returned array. This is extremely useful for generating lists of specific data points or creating lookup tables from complex data structures.