Version: 1.0

Type: Function

Category: Math Functions

License: GNU General Public License

Description: Handy drop-in function to replace PHP's stock array_rand, but uses PHP's mt_srand and mt_rand functions. The Mersenne Twister is much more random, and 4 times faster than standard rand() functions.



<?php
/* mt_array_rand - adapted from fake_array_rand func by zak@php.net */
/* copyleft (c) 2002 Will Fischer <wfischer@silverfisch.net> */

function mt_array_rand($array, $num_req = 1)
{
  /* Ensure that $num_req has a sane value */
  $num_req > 0 or $num_req = 1;

  $count = count ($array);

  for ($n=0; $n < $num_req; ++$n)
  {
    /* Seed the thing, for versions < 4.2.0 */
    mt_srand ((double) microtime() * 10000000);
    $randval = mt_rand();

    /* Use the random value to 'pick' an entry from the array */
    /* Count the number of times that the entry is picked */
    ++$index[$randval % $count];
  }

  /* Loop through the array */
  for ($n = 0; $n < $count; ++$n, next($array))
  {
    /* When we get to an entry that has been picked
       Put the entry into an array for output
       Don't forget to decrease the counter */
    while ($index[$n])
    {
      $out[] = key ($array);
      --$index[$n];
    }
  }

  /* Return a string if only on random key was asked for, otherwise return an array */
  return ($num_req == 1) ? $out[0] : $out ;
}

?>