How to remove duplicates from an array of arrays by a field
Short answer
array_column() with a third argument makes the field the key — equal keys collapse:
<?php
$users = [
['email' => 'a@x.com', 'name' => 'Anna'],
['email' => 'b@x.com', 'name' => 'Oleg'],
['email' => 'a@x.com', 'name' => 'Ann'],
];
$unique = array_values(array_column($users, null, 'email'));
echo json_encode(array_column($unique, 'name'));Output:
["Ann","Oleg"]Keeping the first record
The approach above keeps the last of the equal ones. To keep the first, add a record only when the key is not there yet:
<?php
$users = [
['email' => 'a@x.com', 'name' => 'Anna'],
['email' => 'b@x.com', 'name' => 'Oleg'],
['email' => 'a@x.com', 'name' => 'Ann'],
];
$unique = [];
foreach ($users as $user) {
$unique[$user['email']] ??= $user;
}
echo json_encode(array_column($unique, 'name'));Output:
["Anna","Oleg"]Functions used in this recipe
- array_column — Pulls the values of one key out of an array of arrays.
- array_values — Returns the values of an array with keys numbered from zero.
- array_unique — Removes duplicate values from an array.