Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>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.</p> <p>Therefore your best bet would be to detect collisions and just retry (which could be very expensive in your particular case).</p> <p>If you are constrained to just 7 chars, there's not much you can do above:</p> <pre><code>$allowed_chars = 'abcdefghijklmnopqrstuvwxz'; $allowed_count = strlen($allowed_chars); $password = null; $password_length = 7; while($password === null || already_exists($password)) { $password = ''; for($i = 0; $i &lt; $password_length; ++$i) { $password .= $allowed_chars{mt_rand(0, $allowed_count - 1)}; } } </code></pre> <p>This should eventually give you a new password.</p> <p>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. <code>md5</code>). Then you can make it easier on yourself and less error prone:</p> <pre><code>$password = time(); // even better if you have some other "random" input to use here do { $password = md5(time().$password); } while (already_exists($password)); </code></pre> <p>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 <code>already_exists</code> function.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload