PHP

Extract Unique Values from a Specific Array Key

Learn how to efficiently extract all unique values for a particular key from an array of associative arrays, useful for filtering, summarizing, or populating dropdowns.

<?php
/**
 * Extracts all unique values from a specific key across an array of arrays.
 *
 * @param array $array The input array of associative arrays.
 * @param string $key The key whose values should be extracted.
 * @return array An array containing only the unique values for the specified key.
 */
function get_unique_values_from_key(array $array, string $key): array
{
    // Use array_column to get all values for the specified key
    $columnValues = array_column($array, $key);

    // Use array_unique to get only the unique values
    return array_values(array_unique($columnValues));
}

// Example usage:
$products = [
    ['id' => 101, 'name' => 'Laptop', 'category' => 'Electronics', 'brand' => 'BrandA'],
    ['id' => 102, 'name' => 'Mouse', 'category' => 'Electronics', 'brand' => 'BrandB'],
    ['id' => 103, 'name' => 'Keyboard', 'category' => 'Electronics', 'brand' => 'BrandA'],
    ['id' => 201, 'name' => 'T-Shirt', 'category' => 'Apparel', 'brand' => 'BrandC'],
    ['id' => 202, 'name' => 'Jeans', 'category' => 'Apparel', 'brand' => 'BrandB']
];

$uniqueCategories = get_unique_values_from_key($products, 'category');
// Expected: ['Electronics', 'Apparel']
print_r($uniqueCategories);

$uniqueBrands = get_unique_values_from_key($products, 'brand');
// Expected: ['BrandA', 'BrandB', 'BrandC']
print_r($uniqueBrands);
?>
How it works: This snippet provides a concise way to extract all unique values associated with a specific key from an array of associative arrays. It leverages `array_column` to first gather all values for the designated key and then uses `array_unique` to filter out duplicates. Finally, `array_values` re-indexes the resulting array numerically. This is highly useful for generating distinct lists like dropdown options, category filters, or summary reports.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs