PHP
Extract Column from Array of Associative Arrays in PHP
Efficiently extract values from a specific key (column) from an array of associative arrays or objects in PHP, optionally using another key for the output array's keys, ideal for data processing.
<?php
$users = [
['id' => 101, 'name' => 'Alice', 'email' => '[email protected]'],
['id' => 102, 'name' => 'Bob', 'email' => '[email protected]'],
['id' => 103, 'name' => 'Charlie', 'email' => '[email protected]']
];
// Extract all 'name' values
$names = array_column($users, 'name');
echo "Extracted Names:
";
print_r($names);
// Extract 'email' values, using 'id' as the keys for the new array
$emailsById = array_column($users, 'email', 'id');
echo "
Extracted Emails (keyed by ID):
";
print_r($emailsById);
// Example with missing column (will return null for that entry)
$items = [
['code' => 'A1', 'price' => 100],
['code' => 'B2'] // 'price' is missing
];
$itemPrices = array_column($items, 'price');
echo "
Extracted Item Prices (with missing value):
";
print_r($itemPrices);
?>
How it works: The `array_column()` function is a highly efficient built-in PHP function for extracting a single column (i.e., values associated with a specific key) from an array of associative arrays or objects. It takes the input array, the key whose values you want to retrieve, and an optional third argument for the key to use as the indexes of the output array. This function is extremely useful for transforming a list of records into a simpler list of specific data points or for creating lookup tables. If a specified column is missing for an entry, `array_column()` will return `null` for that entry by default.