Pull random values from an array with PHP

Josh Sherman
2 min read
Software Development PHP

Like most things, you can solve this problem with a number of different approaches. Without knowing about array_rand in PHP, you could end up doing something like this to pull a random value from an array:

$array = ['one', 'two', 'three', 'four', 'five'];
echo $array[0];

The array is shuffled and grabbing the first index yields a random value. If you wanted to pull more than one value, you could reference other indexes. This is great, but what if you needed to keep the original array in order because you needed to use it later in your code? You could generate a random number and pull the item out of the array:

$array  = ['one', 'two', 'three', 'four', 'five'];
$random = mt_rand(0, count($array) - 1);
echo $array[$random];

That also works well, but what if you wanted more than one value? You could run the random number generator multiple times but there’s no guarantee that you won’t generate the same number each time. Let’s try it again using array_rand which returns an array of random keys from the array:

$array  = ['one', 'two', 'three', 'four', 'five'];
$random = array_rand($array);
echo $array[$random];

And if we wanted more than one value, we could pass it a second argument:

$array  = ['one', 'two', 'three', 'four', 'five'];
$random = array_rand($array, 2);
echo $array[$random[0]];
echo $array[$random[1]];

As you can see, there are many ways to skin this cat. All of these solutions are valid depending on what your requirements are. Got another way to pull a random value out of an array that I didn’t mention? Post it in the comments below!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles