Zend - The PHP Company




Arrays

Add Code


Randomize an array  

Type: code fragment
Added by: ADMIN
Entered: 18/01/2000
Last modified: 08/12/1999
Rating: **** (5 votes)
Views: 8496
This function will randomize an array (by Richard Lynch)


<?php
//Use &$array to avoid stack explosion.
//PHP4 probably needs something slightly different
//since it has true references & counting.
function shuffle(&$array){
  
//Assumes array is 0-based integer keys
  //Initialize the random number generator once, and only once,
  //Even if we call shuffle function twice in one script.
  
  
if (!isset($randinit)){
    
srand((double) microtime() * 1000000);
    static 
$randinit 1;
  }
  
  
//Start at the end and work our way forward,
  //always swapping a randomly selected item
  //with the current 'last' one.
  
$last count($array);
  while (
$last 1){
    
    
//Earlier versions of PHP had different args for rand().
    
$random rand(0$last);
    
    
//Swap the randomly selected element with the last element.
    
$temp $array[$random];
    
$array[$random] = $array[$last];
    
$array[$last] = $temp;
    
    
//Move 'forward' in array
    
$last--;
  }
  return 
1;
}


?>


Usage Example


<?php
$test 
= array(12345);
shuffle($test);
while (list(,
$item) = each($test)){
  echo 
$test"<BR>n";
}
?>


Rate This Script





Search



This Category All Categories