How to Get 2 random elements from a PHP array?
From time to time, we may need to randomly select multiple keys from a PHP array.
We have attached 2 different PHP methods to get your random values from your PHP array. Bother super easy to implement.
One method using array_rand() and the other using the array_intersect_key() function.
If you want to get two random values, you can use the function array_rand twice in your PHP code, and then use the keys to get the following values.
$array = [ 0 => 'word 1', 1 => 'word 2', 2 => 'word 3', 3 => 'word 4', ]; $key1 = array_rand($array); $key2 = array_rand($array); $value1 = $array[$key1]; $value2 = $array[$key2];
There is also another solution using array_intersect_key as shown below:
$array = [ 0 => 'word 1', 1 => 'word 2', 2 => 'word 3', 3 => 'word 4', ]; $random_keys = array_rand($array, 2); $random_values = array_intersect_key($array, array_flip($random_keys)); $resetKeys = array_values($random_values); echo $resetKeys . ' ' . $resetKeys;
In the above solution, we used the array_values function to reset the keys from 0 to n. Otherwise your keys will also be in a random order.
If this helped you, please share this page with other devs!
As an Amazon Associate I earn from qualifying purchases. This post may contain affiliate links which means I may receive a commission for purchases made through links.