PHP
Extracting a Specific Column from an Array of Associative Arrays
Efficiently retrieve all values from a particular key across an array of associative arrays (like database rows) using PHP's `array_column()` function.
<?php
$records = [
['id' => 101, 'name' => 'Alice', 'age' => 30],
['id' => 102, 'name' => 'Bob', 'age' => 24],
['id' => 103, 'name' => 'Charlie', 'age' => 35]
];
// Extract all 'name' values
$names = array_column($records, 'name');
echo "Names:
";
print_r($names);
// Extract 'age' values, using 'id' as the keys for the new array
$agesById = array_column($records, 'age', 'id');
echo "
Ages by ID:
";
print_r($agesById);
$products = [
['sku' => 'A101', 'item' => 'Laptop', 'price' => 1200],
['sku' => 'B202', 'item' => 'Mouse', 'price' => 25],
['sku' => 'C303', 'item' => 'Keyboard', 'price' => 75]
];
// Extract 'price' values, using 'sku' as keys
$productPrices = array_column($products, 'price', 'sku');
echo "
Product Prices by SKU:
";
print_r($productPrices);
?>
How it works: `array_column()` is a highly efficient function introduced in PHP 5.5 for extracting a single column (i.e., values for a specific key) from an array of associative arrays or objects. It can optionally use another column's values as the keys for the new array. This is extremely useful when dealing with data retrieved from databases or APIs, allowing developers to quickly get a list of specific attributes (like names or prices) or create a lookup array indexed by a unique identifier (like user IDs or product SKUs).