Pull random values from an array with 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'
shuffle($array
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!

Josh Sherman - The Man, The Myth, The Avatar

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.


If you found this article helpful, please consider buying me a coffee.