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?
I came up with these two functions:
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)
I disagree with your statement:
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:You can test this function as:
But still I will suggest you to use predefined functions as they are well tested by developers.