PHP
Extract Unique Values from Associative Arrays by Key
Efficiently retrieve all unique values for a specific key across an array of associative arrays, useful for generating distinct lists for filters or dropdowns.
<?php
$products = [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25],
['id' => 3, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
['id' => 4, 'name' => 'Desk', 'category' => 'Furniture', 'price' => 300],
['id' => 5, 'name' => 'Chair', 'category' => 'Furniture', 'price' => 150],
['id' => 6, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 400]
];
// Get all unique categories
$uniqueCategories = array_unique(array_column($products, 'category'));
echo "Original Products Array:
";
print_r($products);
echo "
Unique Categories:
";
print_r($uniqueCategories);
// You can also use array_values to reset numeric keys if preferred
$uniqueCategories = array_values($uniqueCategories);
echo "
Unique Categories (re-indexed):
";
print_r($uniqueCategories);
?>
How it works: This snippet demonstrates how to extract all unique values for a specific key from an array of associative arrays. It leverages two powerful PHP array functions: `array_column()` and `array_unique()`. First, `array_column()` extracts all values associated with the specified key (e.g., 'category') into a new, simple numeric array. Then, `array_unique()` processes this new array, removing any duplicate values and returning an array where each value appears only once. Optionally, `array_values()` can be used to re-index the resulting array if you prefer sequential numeric keys.