Randomize array

This function simply randomizes array values.

// 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;
}
Snippet Details



/*
** Example:
*/
 
$test_array = array('why','dont','visit','www','jonas','john','de',':-)');
 
print implode(", ", $test_array);
print "\n";
print implode(", ", RandomizeArray($test_array));
 
/*
Example output:
 
why, dont, visit, www, jonas, john, de, :-)
www, de, jonas, john, visit, why, :-), dont
*/

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

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