Last active
January 12, 2021 01:27
-
-
Save marcsoler/eba1076e8db78e4c1f43ba6f5f6e6be7 to your computer and use it in GitHub Desktop.
Shuffle associative array while preserving keys (Fisher–Yates shuffle 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 | |
function fisherYatesShuffleAssoc(&$items, $seed) | |
{ | |
$di = $items; | |
@mt_srand($seed); | |
$items = array_values($items); | |
for ($i = count($items) - 1; $i > 0; $i--) | |
{ | |
$j = @mt_rand(0, $i); | |
$tmp = $items[$i]; | |
$items[$i] = $items[$j]; | |
$items[$j] = $tmp; | |
} | |
foreach($items as $k => $v) { | |
foreach($di as $dk => $dv) { | |
if($v == $dv) { | |
$items[$dk] = $dv; | |
unset($items[$k]); | |
} | |
} | |
} | |
} | |
//Example seed: | |
$id = 1; | |
//Example assoc. array: | |
$ph = [ | |
'one' => 'One', | |
'two' => 'Two', | |
'three' => 'Three', | |
'four' => 'Four', | |
'five' => 'Five', | |
'six' => 'Six' | |
]; | |
fisherYatesShuffleAssoc($ph, $id); | |
print_r($ph); | |
/* Returns: | |
Array | |
( | |
[four] => Four | |
[six] => Six | |
[three] => Three | |
[one] => One | |
[five] => Five | |
[two] => Two | |
) | |
*/ | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment