faqts : Computers : Programming : Languages : PHP : Common Problems : Arrays

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

29 of 37 people (78%) answered Yes
Recently 7 of 10 people (70%) answered Yes

Entry

How can I randomly shuffle the contents of an array?

Feb 26th, 2002 12:23
Philip Olson, Andrei Zmievski, Nathan Wallace, Richard Lynch


PHP has the shuffle() function, see:

  http://www.php.net/shuffle

A related function is array_rand().  Regarding shuffle, this is an
example from the PHP manual:

  srand ((float)microtime()*1000000);
  shuffle ($arr);

The array $arr is now randomly shuffled.  If you happen to use PHP3,
then consider the following:

<?php
  function rand_shuffle($array){
    //Randomly arranges elements in the array.
    //Returns the shuffled array.
    //This particular algorithm is O(n)
    
    //Take care to call srand once, and only once
    //in any given script.
    static $srand;
    if (!isset($srand) || !$srand){
      $srand = 1;
      srand((double) microtime() * 1000000);
    }
    
    $count = count($array);
    for ($i = 0; $i < $count; $i++){
      //Your version of PHP may need a different syntax to
      //generate a random number between $i and $count
      //Perhaps rand() % ($count - $i) + $i
      //More details in the PHP manual under 'rand' function
      $rindex = rand($i, $count);
      $temp = $array[$i];
      $array[$i] = $array[$rindex];
      $array[$rindex] = $temp;
    }
    
    return $array;
  }
?>