PHP
Extract Unique Values from Array of Associative Arrays
Learn to quickly extract a specific column's values from an array of associative arrays using `array_column`, then get only unique values with `array_unique`.
$users = [
['id' => 1, 'name' => 'Alice', 'email' => '[email protected]'],
['id' => 2, 'name' => 'Bob', 'email' => '[email protected]'],
['id' => 3, 'name' => 'Charlie', 'email' => '[email protected]'],
['id' => 4, 'name' => 'Alice', 'email' => '[email protected]'], // Duplicate name
];
// Extract all names
$allNames = array_column($users, 'name');
// var_dump($allNames); // Expected: ["Alice", "Bob", "Charlie", "Alice"]
// Extract unique names
$uniqueNames = array_unique(array_column($users, 'name'));
// var_dump($uniqueNames); // Expected: ["Alice", "Bob", "Charlie"]
// Extract emails and use 'id' as keys in the resulting array
$emailsById = array_column($users, 'email', 'id');
// var_dump($emailsById);
/*
array(4) {
[1]=> "[email protected]"
[2]=> "[email protected]"
[3]=> "[email protected]"
[4]=> "[email protected]"
}
*/
How it works: This snippet demonstrates the powerful `array_column` function for extracting values from a specific key within an array of associative arrays. It can extract just the values, or it can also map another key's value to become the new key of the resulting array. Combining it with `array_unique` provides an efficient way to get a list of distinct values for a particular column, which is very common in data processing tasks.