PHP
Extracting Specific Columns from an Array of Arrays
Learn to efficiently extract values from a single column of a multidimensional PHP array using the `array_column()` function, creating a simple indexed array of those values.
<?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 'first_name' column
$firstNames = array_column($records, 'first_name');
echo json_encode($firstNames); // Output: ["John","Jane","Peter"]
// Extract 'id' column, using 'first_name' as the keys for the new array
$idsWithNamesAsKeys = array_column($records, 'id', 'first_name');
echo json_encode($idsWithNamesAsKeys); // Output: {"John":1,"Jane":2,"Peter":3}
?>
How it works: The `array_column()` function returns the values from a single column in the input array. It can optionally take a third argument to specify a column to use as the keys for the returned array. This is extremely useful for quickly extracting specific data points from a list of records without manual iteration, as shown by extracting names and then IDs with names as keys.