note 92267 deleted from function.shuffle by danbrown
| From: | danbrown@php.net | Date: | Thu, 16 Jul 2009 22:39:02 +0000 |
| Subject: | note 92267 deleted from function.shuffle by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-158387@lists.php.net to get a copy of this message | ||
Note Submitter: Kaza55
----
Randomizes the elements in your 1D array without using shuffle().
Feel free to use, no credit required!
<?php
function my_shuffle_array($array){
$size = count($array);
$first_key = array_shift(array_keys($array));
$second_key = array_pop(array_keys($array));
if($first_key == $second_key){return $array;}
for($i=1;$i<=(rand(1,$size)*$size);$i++){
$r1=rand($first_key,$second_key);
$r2=rand($first_key,$second_key);
while( $r1==$r2 || !array_key_exists($r1,$array) || !array_key_exists($r2,$array) ){
$r1=rand($first_key,$second_key);
$r2=rand($first_key,$second_key);
}
$temp = $array[$r1];
$array[$r1] = $array[$r2];
$array[$r2] = $temp;
}
return $array;
}
?>
As you can see, it returns the shuffled array.