Generate unique random alphanumeric characters that are 7 characters long

前端 未结 15 727
予麋鹿
予麋鹿 2020-12-09 00:32

It need not be meaningful words - more like random password generation, but the catch is - they should be unique. I will be using this for some kind of package / product cod

15条回答
  •  失恋的感觉
    2020-12-09 01:15

    It is generally not possible to generate sequences with both unique and random elements: obviously to be unique the algorithm has to take into account the previously generated elements in the sequence, so the next ones will not really be random.

    Therefore your best bet would be to detect collisions and just retry (which could be very expensive in your particular case).

    If you are constrained to just 7 chars, there's not much you can do above:

    $allowed_chars = 'abcdefghijklmnopqrstuvwxz';
    $allowed_count = strlen($allowed_chars);
    $password = null;
    $password_length = 7;
    
    while($password === null || already_exists($password)) {
        $password = '';
        for($i = 0; $i < $password_length; ++$i) {
            $password .= $allowed_chars{mt_rand(0, $allowed_count - 1)};
        }
    }
    

    This should eventually give you a new password.

    However, in similar cases I have encountered I usually pick a larger password size which also happens to be the size of the hex representation of a popular hash function (e.g. md5). Then you can make it easier on yourself and less error prone:

    $password = time(); // even better if you have some other "random" input to use here
    
    do {
        $password = md5(time().$password);
    }
    while (already_exists($password));
    

    This also has the added advantage that the sequence space is larger, hence there will be less collisions. You can pick the size of the hash function according to the expected numbers of passwords you will generate in the future to "guarantee" a low collision probability and thus less calls to the possibly expensive already_exists function.

提交回复
热议问题