I have an array called $ran = array(1,2,3,4);
I need to get a random value out of this array and store it in a variable, how can I do this?
I have an array called $ran = array(1,2,3,4);
I need to get a random value out of this array and store it in a variable, how can I do this?
One line: $ran[rand(0, count($ran) - 1)]
The
array_rand
function seems to have an uneven distribution on large arrays, not every array item is equally likely to get picked. Using shuffle on the array and then taking the first element doesn't have this problem:or, for arrays specifically:
I'm basing my answer off of @ÓlafurWaage's function. I tried to use it but was running into reference issues when I had tried to modify the return object. I updated his function to pass and return by reference. The new function is:
For more context, see my question over at Passing/Returning references to object + changing object is not working
You could use the array_rand function to select a random key from your array like below.
or you could use the rand and count functions to select a random index.
Use rand() to get random number to echo random key. In ex: 0 - 3