Randomize array

This function simply randomizes array values.

Snippet information

Author:
Jonas John

License:
Public Domain

Language:
PHP

Created:
01/16/2007

Updated:
09/10/2007

Tags:
,

Related links:
- Function: shuffle


// I noticed that there is already a built-in function that
// does the same - so don't use mine ;-)
//
// --> shuffle($Array);
//
// http://de2.php.net/manual/de/function.shuffle.php
//
 
function RandomizeArray($array){
 
    // error check:
    $array = (!is_array($array)) ? array($array) : $array;
 
    $a = array();
    $max = count($array) + 10;
 
    while(count($array) > 0){        
        $e = array_shift($array);
        $r = rand(0, $max);
 
        // find a empty key:
        while (isset($a[$r])){
            $r = rand(0, $max);
        }        
        $a[$r] = $e;
    }
 
    ksort($a);
    $a = array_values($a);
 
    return $a;
}


Found a bug? Or do you have a better solution for this?
Feel free to leave a message:

Add a comment


Leave a comment

VitCOM Photo February 14, 2009 at 14:34
php -> shuffle