PHP: Better than array_rand() [Q&A]

2019-08-07 08:08发布

问题:

There are times where array_rand() is not good enough.

Although I know that it returns keys and not values, I find its name unclear.

But most importantly, array_rand() does not give equal chances to all keys (as seen in Array_rand does not shuffle or Array_rand not random and plenty of other examples).

A notable way to better randomize the array is the function shuffle() but it can be quite ressources demanding, plus if the keys are important, well they are lost with it.

What would be a good and faster alternative to that slightly clumsy function?

回答1:

I came up with these two functions:

function random_key($array){
    $keys=array_keys($array);
    return $keys[mt_rand(0, count($keys) - 1)];
}

function random_value($array){
    $values=array_values($array);
    return $values[mt_rand(0, count($values) - 1)];
}

They both work well with any kind of arrays, do not alter the original one, are giving more realistic random results, and their names are self describing.

The main drawback is that as opposed to array_rand, they can only gives one element.

(Helped with an answer from How to get random value out of an array)



回答2:

I disagree with your statement:

array_rand() does not give equal chances to all keys.

Pre-defined functions such as array_rand() are designed to do what they're made for but if somehow you don't want to rely on this and want to use your own you can try something like this:

function array_rand_alternative($array){
  return rand(0,count($array)-1);
}

You can test this function as:

$a=[5,2,1,3];
for($i=0;$i<10;$i++)
  echo array_rand_alternative($a).",";

But still I will suggest you to use predefined functions as they are well tested by developers.