title: PHP function to generate v4 UUID
body: <p>So I've been doing some digging around and I've been trying to piece together a function that generates a valid v4 UUID in PHP. This is the closest I've been able to come. My knowledge in hex, decimal, binary, PHP's bitwise operators and the like is nearly nonexistent. This function generates a valid v4 UUID up until one area. A v4 UUID should be in the form of:</p>
  <blockquote>
  <p>xxxxxxxx-xxxx-<strong>4</strong>xxx-<strong>y</strong>xxx-xxxxxxxxxxxx</p>
  </blockquote>
  <p>Where <strong>y</strong>  is 8, 9, A, or B. This is where the functions fails as it doesn't adhere to that.</p>
  <p>I was hoping someone with more knowledge than me in this area could lend me a hand and help me fix this function so it does adhere to that rule.</p>
  <p>The function is as follows:</p>
  <pre><code>&lt;?php
  
  function gen_uuid() {
   $uuid = array(
    'time_low'  =&gt; 0,
    'time_mid'  =&gt; 0,
    'time_hi'  =&gt; 0,
    'clock_seq_hi' =&gt; 0,
    'clock_seq_low' =&gt; 0,
    'node'   =&gt; array()
   );
   
   $uuid['time_low'] = mt_rand(0, 0xffff) + (mt_rand(0, 0xffff) &lt;&lt; 16);
   $uuid['time_mid'] = mt_rand(0, 0xffff);
   $uuid['time_hi'] = (4 &lt;&lt; 12) | (mt_rand(0, 0x1000));
   $uuid['clock_seq_hi'] = (1 &lt;&lt; 7) | (mt_rand(0, 128));
   $uuid['clock_seq_low'] = mt_rand(0, 255);
   
   for ($i = 0; $i &lt; 6; $i++) {
    $uuid['node'][$i] = mt_rand(0, 255);
   }
   
   $uuid = sprintf('%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x',
    $uuid['time_low'],
    $uuid['time_mid'],
    $uuid['time_hi'],
    $uuid['clock_seq_hi'],
    $uuid['clock_seq_low'],
    $uuid['node'][0],
    $uuid['node'][1],
    $uuid['node'][2],
    $uuid['node'][3],
    $uuid['node'][4],
    $uuid['node'][5]
   );
   
   return $uuid;
  }
  
  ?&gt;
  </code></pre>