PHP
Extract Unique Values from Array of Associative Arrays by Key
Discover how to efficiently extract a list of unique values for a specific key from an array where each element is an associative array or object.
<?php
$products = [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics'],
['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics'],
['id' => 3, 'name' => 'Keyboard', 'category' => 'Electronics'],
['id' => 4, 'name' => 'T-Shirt', 'category' => 'Apparel'],
['id' => 5, 'name' => 'Jeans', 'category' => 'Apparel'],
['id' => 6, 'name' => 'Monitor', 'category' => 'Electronics'],
['id' => 7, 'name' => 'Headphones', 'category' => 'Audio'],
['id' => 8, 'name' => 'Speakers', 'category' => 'Audio'],
];
// Method 1: Using array_column and array_unique
$categories = array_column($products, 'category');
$uniqueCategories = array_unique($categories);
echo "Unique Categories (Method 1):
";
print_r($uniqueCategories);
// Method 2: Manual iteration (useful if array_column is not available or for more complex logic)
$uniqueCategoriesManual = [];
foreach ($products as $product) {
$uniqueCategoriesManual[$product['category']] = true;
}
$uniqueCategoriesManual = array_keys($uniqueCategoriesManual);
echo "
Unique Categories (Method 2):
";
print_r($uniqueCategoriesManual);
// Expected Output:
// Array
// (
// [0] => Electronics
// [3] => Apparel
// [6] => Audio
// )
How it works: This snippet shows two methods to extract unique values for a specific key from an array of associative arrays. Method 1 leverages `array_column()` to get all values for the specified key into a new array, and then `array_unique()` to filter out duplicates. Method 2 iterates through the array, using the key's value as a key in a temporary associative array, effectively creating unique entries, and then uses `array_keys()` to get the final list of unique values.