This post will discuss how to generate random entries from an array in PHP.

1. Using array_rand() function

A simple and efficient solution is to use the array_rand() function to pick one or more random entries out of an array. Here’s a PHP program to pick a random key from an array $arr:

Download  Run Code

 
The array_rand() function returns the key of the random entry. To select a random value (not a key) of the random entry, use the snippet below:

Download  Run Code

 
Here’s an example using a closure.

Download  Run Code

 
The second argument of the array_rand() function specifies how many random entries should be picked. Here’s a PHP program to pick $n random values from an array $arr:

Download  Run Code

 
See PHP Manual for more details.

2. Using mt_rand() function

Before PHP 7.1.0, the internal randomization algorithm for array_rand() uses the libc rand function, which is slower and less-random than Mersenne Twister Number Generator. If your array keys are numeric, here’s a better alternative to pick a random value from an array $arr:

Download  Run Code

 
The mt_rand() function is a better alternative for the older rand(). However, both array_rand() and mt_rand() does not generate cryptographically secure values. For cryptographic purposes, consider using random_int(), random_bytes(), or openssl_random_pseudo_bytes() instead.

 
Refer to PHP Manual for more details.

That’s all about generating random entries from an array in PHP.