PHP
Randomly Shuffle Associative Array Preserving Keys
Learn how to randomly reorder an associative array in PHP while maintaining the key-value pair associations, as `shuffle()` resets numeric keys.
<?php
$associativeArray = [
'apple' => 'red',
'banana' => 'yellow',
'grape' => 'purple',
'orange' => 'orange',
'kiwi' => 'green'
];
// Method 1: Using uksort with random comparison
$shuffledArray1 = $associativeArray;
uksort($shuffledArray1, function($a, $b) {
return mt_rand(-1, 1);
});
print_r($shuffledArray1);
// Method 2: Create temporary random keys, sort, then reconstruct (more controlled randomness)
$keys = array_keys($associativeArray);
shuffle($keys);
$shuffledArray2 = [];
foreach ($keys as $key) {
$shuffledArray2[$key] = $associativeArray[$key];
}
print_r($shuffledArray2);
/* Expected Output (order will vary each run):
Array
(
[banana] => yellow
[kiwi] => green
[orange] => orange
[apple] => red
[grape] => purple
)
Array
(
[orange] => orange
[banana] => yellow
[apple] => red
[grape] => purple
[kiwi] => green
)
*/
?>
How it works: This snippet demonstrates two methods to randomly shuffle an associative array while ensuring that the key-value pair associations are preserved. PHP's `shuffle()` function reorders elements but discards original keys, reindexing numerically. Method 1 uses `uksort` with a custom comparison function that returns a random value, effectively sorting the array by random key order. Method 2 extracts the keys, shuffles them using `shuffle()`, and then reconstructs the array in the new key order, mapping back to the original values. Both methods achieve the goal of randomizing the order while keeping keys intact.