PHP
Extracting a Column from Arrays with array_column
Efficiently extract specific column values from a multi-dimensional PHP array or array of objects into a simple, flat array using array_column().
<?php
$records = [
['id' => 2135, 'first_name' => 'John', 'last_name' => 'Doe'],
['id' => 3245, 'first_name' => 'Sally', 'last_name' => 'Smith'],
['id' => 5342, 'first_name' => 'Jane', 'last_name' => 'Jones'],
['id' => 5623, 'first_name' => 'Peter', 'last_name' => 'Pan'],
];
// Get an array of just the 'first_name' values
$firstNames = array_column($records, 'first_name');
print_r($firstNames);
// Get an array of 'id' values, using 'last_name' as the keys
$idByLastName = array_column($records, 'id', 'last_name');
print_r($idByLastName);
?>
How it works: This snippet showcases the `array_column()` function, a highly useful tool for working with arrays of arrays or objects. It efficiently extracts all values for a single specified key ('first_name' in the first example) into a new, one-dimensional array. The second example further demonstrates its power by extracting 'id' values while using 'last_name' values as the keys for the resulting array, simplifying data restructuring.