Skip to content

Instantly share code, notes, and snippets.

@wolf-dog
Created May 27, 2014 14:06
Show Gist options
  • Save wolf-dog/e6bb9a6f9851660ec37e to your computer and use it in GitHub Desktop.
Save wolf-dog/e6bb9a6f9851660ec37e to your computer and use it in GitHub Desktop.
PHP function to replace array_rand(), using mt_rand()
<?php
function mt_array_rand(Array $array, $num = 1)
{
$count = count($array);
if ($num > $count) {
return null;
}
$keys = array_keys($array);
$res = [];
for ($i = 0; $i < $num;) {
$rand = mt_rand(0, $count - 1);
if (isset($res[$keys[$rand]])) {
continue;
}
$res[$keys[$rand]] = $i;
$i++;
}
$res = array_flip($res);
sort($res);
return (count($res) === 1) ? reset($res) : $res;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment