Random numbers with rand() and one seed
<p>I have to generate a large number of unique keys. One key should consist of 16 digits. I came up with the following code:</p>

<pre><code>function make_seed()
{
    list($usec, $sec) = explode(' ', microtime());
    return (float) $sec + ((float) $usec * 100000);
}
function generate_4_digits(){
    $randval = rand(100, 9999);
    if($randval &lt; 1000){
        $randval = '0'.$randval;
    }
    return (string)$randval;
}
function generate_cdkey(){
    return generate_4_digits() . '-' . generate_4_digits() . '-' . generate_4_digits() . '-' . generate_4_digits();
}


srand(make_seed());
echo generate_cdkey();
</code></pre>

<p>The result was quite promising, <code>6114-0461-7825-1604</code>.
Then I decided to generate 10 000 keys and see how many duplicates I get:</p>

<pre><code>srand(make_seed());
$keys = array();
$duplicates = array();
for($i = 0; $i &lt; 10000; $i++){
    $new_key = generate_cdkey();
    if(in_array($new_key, $keys)){
        $duplicates[] = $new_key;
    }
    $keys[] = $new_key;
}
$keys_length = count($keys);
var_dump($duplicates);
echo '&lt;pre&gt;';
for($i = 0; $i &lt; $keys_length; $i++){
    echo $keys[$i] . "\n";
}
echo '&lt;/pre&gt;';
</code></pre>

<p>On first run I got <code>1807</code> duplicates which was quite disappointing. But for my great surprise on each following run I get the same number of duplicates!? When I looked closely at the generated keys, I realized the last <code>1807</code> keys were exactly the same as the first ones. So I can generate <code>8193</code> without a single duplicate?! This is so close to 2^13?! Can we conclude <code>rand()</code> is suited to generate maz 2^13 unique numbers? But why?</p>

<p>I changed the code to use <code>mt_rand()</code> and I get no duplicates even when generating 50 000 keys.</p>
