PHP

Unique by Callback

admin by @admin ADMIN
5d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Like array_unique, but the uniqueness test is a callback that returns the key to dedupe by. Useful for "unique by ID" or "unique by lowercased email" across arrays of objects/rows.
PHP
Raw
<?php
function uniqueBy(array $items, callable $keyFn): array {
    $seen = [];
    $out  = [];
    foreach ($items as $item) {
        $k = $keyFn($item);
        if (!array_key_exists($k, $seen)) {
            $seen[$k] = true;
            $out[]    = $item;
        }
    }
    return $out;
}

$users = [
    ['id'=>1,'name'=>'Alice'],
    ['id'=>2,'name'=>'Bob'],
    ['id'=>1,'name'=>'Alice (dup)'],
];

print_r(uniqueBy($users, fn($u) => $u['id']));
// [ {id:1,name:Alice}, {id:2,name:Bob} ]
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.