PHP
Extracting a Specific Column from Multi-dimensional Arrays
Learn how to quickly extract a single column of values from an array of arrays or objects in PHP using `array_column()`, useful for data processing and transformations.
<?php
$users = [
['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]'],
];
// Extract all 'name' values
$names = array_column($users, 'name');
print_r($names);
echo "
";
// Extract 'id' values and use 'name' as keys
$userMap = array_column($users, 'id', 'name');
print_r($userMap);
?>
How it works: The `array_column()` function is highly efficient for extracting values from a single column (or field) in a multi-dimensional array or array of objects. It takes the input array, the column to return, and optionally a column to use as the keys for the output array, streamlining data manipulation tasks by providing a flattened list or a key-value map.