Get a random item from an array in PHP

June 22, 2022  ‐ 1 min read

When picking a random item from an array in PHP there is no need to generate a random index (or key) yourself. PHP wraps this functionality in the built-in array_rand() function, which uses a pseudo random number generator.

This array_rand() function finds a random key in an array, it doesn't return a random element. Therefore we need to retrieve the random element from the array using the key that was returned by array_rand().

<?php

$dice = [1, 2, 3, 4, 5, 6];

$throw = array_rand($dice);

echo $dice[$throw];