Quantcast
Viewing latest article 9
Browse Latest Browse All 15

PHP: Sorting arrays randomly with array_randsort()

Or, you know, just use the shuffle() function. Kim points out the drawbacks of shuffle in the comments below.

A custom PHP function. This function will return an array that’s been resorted in a random order. Supports both numerically-indexed and associative arrays. Uses PHP’s native array_rand() function.

function array_randsort($array,$preserve_keys=false){
	/*-------------------------------------/
	Preserving the keys works best with associative arrays. 
	If you choose to preserve keys on a numerically-indexed or 
    mixed-indexed array, use a foreach loop rather than a for loop 
    to preserve the sorted order.
	/-------------------------------------*/
	
	if(!is_array($array)):
		exit('Supplied argument is not a valid array.');
	else:
		$i = NULL;
	
		// how long is the array?
		$array_length = count($array); 
	
		// Sorts the array keys in a random order. 
		$randomize_array_keys = array_rand($array,$array_length);
		
		// if we are preserving the keys ...
		if($preserve_keys===true) {		
			// reorganize the original array in a new array 
			foreach($randomize_array_keys as $k=>$v){
				$randsort[$randomize_array_keys[$k]] = $array[$randomize_array_keys[$k]];
			}
		} else {
			// reorganize the original array in a new array 
			for($i=0; $i < $array_length; $i++){
				$randsort[$i] = $array[$randomize_array_keys[$i]];
			}
		}
		return $randsort;
	endif;
}

Viewing latest article 9
Browse Latest Browse All 15

Trending Articles