Last active
May 29, 2016 08:53
-
-
Save esase/571f6f5b1426c18ef984 to your computer and use it in GitHub Desktop.
Array shuffle (by Donald Knuth) [algorithm]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$input = [ | |
1, | |
2, | |
3, | |
4, | |
5, | |
6, | |
7 | |
]; | |
/** | |
* Shuffle | |
* | |
* @param array $input | |
* @return array | |
*/ | |
function shuffle_items($input) { | |
$inputLength = count($input); | |
for ($i = 0; $i < $inputLength; $i++) { | |
$randPosition = rand(0, $i); | |
// swap values | |
if ($i <> $randPosition) { | |
$currentValue = $input[$i]; | |
$input[$i] = $input[$randPosition]; | |
$input[$randPosition] = $currentValue; | |
} | |
} | |
return $input; | |
} | |
echo '<pre>'; | |
print_r( shuffle_items($input) ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment