PHP
Extract a Column from Multi-Dimensional Array
Discover `array_column` in PHP to quickly extract values from a single column within an array of associative arrays, useful for lists of records.
<?php
$records = [
['id' => 101, 'product' => 'Laptop', 'price' => 1200],
['id' => 102, 'product' => 'Mouse', 'price' => 25],
['id' => 103, 'product' => 'Keyboard', 'price' => 75],
['id' => 104, 'product' => 'Monitor', 'price' => 300],
];
// Extract all product names
$productNames = array_column($records, 'product');
print_r($productNames);
echo "
";
// Extract product names with 'id' as keys
$productsById = array_column($records, 'product', 'id');
print_r($productsById);
?>
How it works: The `array_column` function simplifies the task of extracting values from a specific column in a multi-dimensional array or an array of objects. It can optionally also use another column's values as the keys for the resulting array, making it incredibly versatile for re-indexing or creating lookup tables from database results or other data sources.