How can the PHP code be optimized to improve the efficiency of uidNumber retrieval?

The PHP code can be optimized by reducing the number of LDAP queries made to retrieve uidNumber values. One way to improve efficiency is to fetch all uidNumber values in a single LDAP query and store them in an array for easy retrieval.

<?php

// Connect to LDAP server
$ldapconn = ldap_connect("ldap.example.com");

// Bind with a service account
$ldapbind = ldap_bind($ldapconn, "cn=admin,dc=example,dc=com", "password");

if ($ldapbind) {
    // Search for all uidNumber values
    $result = ldap_search($ldapconn, "ou=users,dc=example,dc=com", "(objectClass=posixAccount)", ["uidNumber"]);
    $entries = ldap_get_entries($ldapconn, $result);

    // Store uidNumber values in an array
    $uidNumbers = [];
    foreach ($entries as $entry) {
        if (isset($entry['uidnumber'][0])) {
            $uidNumbers[] = $entry['uidnumber'][0];
        }
    }

    // Example: Retrieve uidNumber for a specific user
    $username = "johndoe";
    $uidNumber = $uidNumbers[array_search($username, $entries['uid'])];

    // Close LDAP connection
    ldap_close($ldapconn);
} else {
    echo "LDAP bind failed";
}

?>