Skip to content

Instantly share code, notes, and snippets.

@esase
Last active May 29, 2016 08:53
Show Gist options
  • Save esase/571f6f5b1426c18ef984 to your computer and use it in GitHub Desktop.
Save esase/571f6f5b1426c18ef984 to your computer and use it in GitHub Desktop.
Array shuffle (by Donald Knuth) [algorithm]
<?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