PHP

Extracting Unique Values from a Column in Multidimensional Arrays

Learn to efficiently extract a list of unique values from a specified column across multiple associative arrays or objects within a PHP array of arrays.

<?php
$users = [
    ['id' => 1, 'name' => 'Alice', 'role' => 'admin', 'department' => 'IT'],
    ['id' => 2, 'name' => 'Bob', 'role' => 'editor', 'department' => 'Marketing'],
    ['id' => 3, 'name' => 'Charlie', 'role' => 'admin', 'department' => 'IT'],
    ['id' => 4, 'name' => 'Diana', 'role' => 'viewer', 'department' => 'Sales'],
    ['id' => 5, 'name' => 'Eve', 'role' => 'editor', 'department' => 'Marketing'],
    ['id' => 6, 'name' => 'Frank', 'role' => 'admin', 'department' => 'HR'],
];

// Get all unique roles
$uniqueRoles = array_unique(array_column($users, 'role'));
// var_dump($uniqueRoles);

/* Expected $uniqueRoles (simplified):
[
    0 => 'admin',
    1 => 'editor',
    3 => 'viewer',
]
*/

// Get all unique departments
$uniqueDepartments = array_unique(array_column($users, 'department'));
// var_dump($uniqueDepartments);

/* Expected $uniqueDepartments (simplified):
[
    0 => 'IT',
    1 => 'Marketing',
    3 => 'Sales',
    5 => 'HR',
]
*/

// Re-index the array to start from 0 for cleaner list
$uniqueRolesReindexed = array_values($uniqueRoles);
// var_dump($uniqueRolesReindexed);

/* Expected $uniqueRolesReindexed (simplified):
[
    0 => 'admin',
    1 => 'editor',
    2 => 'viewer',
]
*/
How it works: This snippet demonstrates a highly efficient way to extract unique values from a specific 'column' within an array of associative arrays (or objects, if PHP 7.0+). It leverages two powerful built-in functions: `array_column()` and `array_unique()`. `array_column()` first extracts all values for the specified key into a new single-dimensional array. Then, `array_unique()` filters out any duplicate values, leaving only the distinct entries. Optionally, `array_values()` can be used to re-index the resulting array numerically, starting from zero, for a cleaner list.

Need help integrating this into your project?

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

Hire DigitalCodeLabs