PHP
Extract a Column from an Array of Arrays in PHP
Learn how to efficiently extract specific values from a designated column within an array of associative arrays using PHP's powerful `array_column()` function.
<?php
$records = [
['id' => 101, 'name' => 'Product A', 'price' => 29.99],
['id' => 102, 'name' => 'Product B', 'price' => 12.50],
['id' => 103, 'name' => 'Product C', 'price' => 75.00]
];
// Extract all 'name' values
$productNames = array_column($records, 'name');
echo "Product Names: " . implode(", ", $productNames) . "
"; // Output: Product Names: Product A, Product B, Product C
// Extract all 'price' values, indexed by 'id'
$productPricesById = array_column($records, 'price', 'id');
echo "<pre>";
print_r($productPricesById);
echo "</pre>";
/*
Output will be:
Product Names: Product A, Product B, Product C
Array
(
[101] => 29.99
[102] => 12.5
[103] => 75
)
*/
?>
How it works: The `array_column()` function is a highly efficient way to retrieve all values from a single 'column' in an array of associative arrays or objects. It can optionally specify a column to use as the keys for the returned array, making it incredibly useful for quickly generating lists or lookup tables from complex, structured data.