Skip to content
PHP Logo

What is the correct way to generate a random element from an array in PHP?

When you need to generate a random element from an array in PHP, you can use the array_rand() function. This function returns a random key from the array, which you can then use to access the corresponding element. By using array_rand(), you can easily select a random element from an array without having to shuffle the entire array.

php
// Example array
$myArray = array('apple', 'banana', 'orange', 'grape', 'kiwi');

// Get a random key from the array
$randomKey = array_rand($myArray);

// Access the random element using the random key
$randomElement = $myArray[$randomKey];

echo $randomElement;