Skip to content
PHP Logo

What is the purpose of using the PHP function array_rand() in generating random numbers?

The PHP function array_rand() is used to generate random numbers by selecting one or more random keys from an array. This function is commonly used when you need to randomly select elements from an array, such as choosing a random item from a list or shuffling the order of elements. By using array_rand(), you can easily introduce randomness into your PHP code and create dynamic, unpredictable behavior.

php
// Example of using array_rand() to generate a random number
$numbers = [1, 2, 3, 4, 5];
$random_key = array_rand($numbers);
$random_number = $numbers[$random_key];

echo "Random number: " . $random_number;