note 7632 modified in shuffle by ronabop

From: Date: Sun, 03 Sep 2000 10:08:26 +0000
Subject: note 7632 modified in shuffle by ronabop
Groups: php.notes 
Request: Send a blank email to php-notes+get-4025@lists.php.net to get a copy of this message
As it has been previously stated, there are problems connected with using shuffle() if you use a solaris-based web-server. This is my case so I have (with a little help) made a Fisher Yates Shuffle routine as you might know it from "perldoc -q shuffle". Here it is: // Fisher-Yates Shuffle an array in place (pass-by-reference) // Converted from "perldoc -q shuffle" function f_y_Shuffle(&$arr) { // Reverse a splice in an array (used by f_y_Shuffle() function reverse_splice(&$splice, $i1, $i2) { if($i1>$i2) { $swp = $i1; $i1 = $i2; $i2 = $swp; } for($k=$i2;$k>=$i1;$k--){$tmpArr[] = $splice[$k];} for($k=0;$k<count($tmpArr);$k++) {$splice[$i1+$k] = $tmpArr[$k];} } $i = count($arr); mt_srand((double)microtime()*1000000); while($i>0) { --$i; $j = @mt_rand(0, $i); if($i!=$j) { reverse_splice($arr, $i, $j); } } } Of course if you use PHP4, you could use array_splice() and array_reverse() instead of the "homemade" reverse_splice(); Take a look at http://www.pert.dk/php/shuffletest.php3 TUI Per Thomsen, Omedia Digital http://www.php.net/manual/function.shuffle.php

« previous php.notes (#4025) next »