PHP
Extract a Single Column from an Array of Arrays
Learn to efficiently extract all values from a specific column (key) across an array of associative arrays into a new indexed array using PHP's `array_column` function.
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]'],
];
// Extract only the 'name' column
$names = array_column($users, 'name');
print_r($names);
// Extract 'name' column and use 'id' as keys
$namesById = array_column($users, 'name', 'id');
print_r($namesById);
?>
How it works: The `array_column()` function provides a straightforward way to extract a specific column from an array of arrays or objects. The first example extracts all 'name' values into a simple indexed array. The second example demonstrates its powerful capability to also use another column ('id' in this case) as the keys for the resulting array, making it perfect for creating lookup tables or lists from database results.