Get random elements from an array in PHP
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:
|
1 2 3 4 |
<?php $arr = array('first' => 'a', 'second' => 'b'); echo array_rand($arr); // first or second ?> |
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:
|
1 2 3 4 |
<?php $arr = array('first' => 'a', 'second' => 'b'); echo $arr[array_rand($arr)]; // `a` or `b` ?> |
Here’s an example using a closure.
|
1 2 3 4 5 6 |
<?php $random = function($arr) {return $arr[array_rand($arr)];}; $arr = array(6, 4, -1, 9, -2); echo $random($arr); ?> |
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:
|
1 2 3 4 5 6 7 8 |
<?php $arr = array(6, 4, -1, 9, -2); $n = 2; $rand_keys = array_rand($arr, $n); echo $arr[$rand_keys[0]] . "\n"; echo $arr[$rand_keys[1]] . "\n"; ?> |
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:
|
1 2 3 4 |
<?php $arr = array(6, 4, -1, 9, -2); echo $arr[mt_rand(0, count($arr) - 1)]; ?> |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)