Shuffling associative array

We have shuffle() to reorder a numeric array, we have array_rand() to randomly pick a specific number of values from an array but there’s no built-in command for shuffling an associative array. After having seen a few pretty bad solutions I decided to offer my own.

  1.  
  2. function ashuffle(&$array) {
  3.   if (!is_array($array)) {
  4.     return false;
  5.   }
  6.  
  7.   $keys = array_keys($array);
  8.   $result = shuffle($keys);
  9.  
  10.   if (!$result) {
  11.     return false;
  12.   }
  13.  
  14.   $randArray = array();
  15.   foreach ($keys as $key){
  16.     $randArray[$key] = $array[$key];
  17.   }
  18.   $array = $randArray;
  19.  
  20.   return true;
  21. }
  22.  

Leave a Reply