mercredi 1 mars 2023

optimal way to create a 12 digit unique random number for users

Issue

I am trying to add a 12 digit long, unique identifier to a user table that is going to be used by the users to find each other.
Since it is will be handed to the users it needs to be unrelated to the auto increment id on the users table.

The two methods that come to my mind are:

loop until you get a unique number

do {
    // get a random 12 digit number
    $identifier = str_pad(rand(0, 999999999999), 12, '0', STR_PAD_LEFT);
    // check if it is unique
    $exists = User::where('identifier', $identifier)->exists();
} while ($exists)

return $identifier

Drawbacks
In theory it could end up in an infinite loop (although almost impossible).

adjust the random number accordingly

// get all the identifiers as array
$identifiers = sort(User::pluck('identifier')->toArray());

// random number becomes lower depending on the total users
$my_identifier = rand(0, 999999999999 - count($identifiers));

// increment for all the smaller identifiers
foreach($identifiers as $identifier) {
    if(intval($identifier) > $my_identifier) break;
    $my_identifier ++;
}

return str_pad($my_identifier, 12, '0', STR_PAD_LEFT)

Drawbacks While this makes sure I don't run into an infinite loop, having to sort an array the length of my user count, and possibly looping through all of it sounds pretty heavy.

Question

The best solution out of these two I think is the first one since the possibility of an infinite loop is basically non existent, while the second solution looks really heavy and impractical.

But is there any way to avoid both drawbacks from these two solutions?




Aucun commentaire:

Enregistrer un commentaire