Function To Find Largest UID Number In LDAP

Updated 2026-09-23: replaced ldap_sort(), which PHP 8 removed.

I got most of this function from this CakePHP Bakery article. It will find all the uidNumbers, sorting them smallest to largest, then return the largest number.

$ds = ldap_connect("localhost");  // assuming the LDAP server is on this host

function findLargestUidNumber($ds)
{
    $s = ldap_search($ds, "ou=people,dc=yourdomain,dc=com", 'uidnumber=*');
    if ($s)
    {
        $result = ldap_get_entries($ds, $s);
        $count = $result['count'];
        unset($result['count']);

        usort($result, function ($a, $b) {
            return (int) $a['uidnumber'][0] <=> (int) $b['uidnumber'][0];
        });

        $biguid = $result[$count-1]['uidnumber'][0];
        return $biguid;
    }
    return null;
}

$largestUID = findLargestUidNumber($ds);