Skip to content

Instantly share code, notes, and snippets.

@hu9o
Created August 25, 2015 13:18
Show Gist options
  • Save hu9o/4220f41e6981ba3301cb to your computer and use it in GitHub Desktop.
Save hu9o/4220f41e6981ba3301cb to your computer and use it in GitHub Desktop.
<?php
/**
* Shuffles an array using mt_rand() instead of rand().
* CAUTION: Unlike shuffle(), returns a new array, leaving the source untouched. It's better that way.
* CAUTION: Won't work with associative arrays. Who would shuffle an associative array anyways?
*
* @param array $deck The index-based array to be shuffled.
* @return array A new array containing exactly the same elements in a random order.
*
* @see http://stackoverflow.com/questions/5694319/how-random-is-phps-shuffle-function
* @see https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle
*/
function mt_shuffle($deck) {
for ($i = count($deck)-1; $i >= 1; $i--) {
$j = mt_rand(0, $i);
list($deck[$j], $deck[$i]) = array($deck[$i], $deck[$j]);
}
return $deck;
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment