2

Randomize array whilst keeping the keys in tact..

Posted by Darren on May 8, 2009 in Coding, PHP

I had a problem recently – I needed to randomize an array – of course I could have used the PHP function array_rand however, this overwrote the existing keys with numbers – not good! as I need to use those keys as part of my display – okay, not best practice but i’d set it up this way thus far, why should I change it? Therefore I discovered a function that allowed me to do exactly what I needed, it randomizes the array whilst keeping the existing keys :) !

function array_rand_keys($array, $limit = 1) {
$count = @count($array)-1;

if ($limit == 0 || !is_array($array) || $limit > $count) return array();
if ($count == 1) return $array;

for ($x = 0; $x < $limit; $x++) {
$rand = rand(0, $count);

while (isset($rands[$rand])) $rand = rand(0, $count);

$rands[$rand] = $rand;
}

$return = array();
$curr = current($rands);

while (count($return) != $limit) {
$cur = 0;

foreach ($array as $key => $val) {
if ($cur == $curr) {
$return[$key] = $val;

$curr = next($rands);
continue 2;
} else {
$cur++;
}
}
}

return $return;
}

Tags: , ,