PHP array_rand Function Explained

The array_rand() function is a built-in function in PHP that is used to randomly select one or more keys from an array and return them.

The syntax of the array_rand() function is as follows:

array_rand(array $array, int $num = 1): mixed

In this case, $array is an array from which keys are to be selected, and $num is the number of keys to be chosen. By default, the value of $num is 1, meaning only one key is selected.

The array_rand() function randomly selects a specified number of keys from a given array and returns them as a new array. The selected keys will maintain the original order and indexing of the array.

Here are a few examples:

$fruits = array('apple', 'banana', 'orange', 'grape', 'mango');

// 从 $fruits 数组中随机选择一个键
$randomKey = array_rand($fruits);

echo $fruits[$randomKey]; // 输出随机选择的水果名称

// 从 $fruits 数组中随机选择两个键
$randomKeys = array_rand($fruits, 2);

foreach ($randomKeys as $key) {
    echo $fruits[$key] . ' '; // 输出随机选择的两个水果名称
}

In the above examples, the array_rand() function randomly selects keys from the $fruits array and outputs the corresponding fruit names. In the second example, the array_rand() function selects two keys and outputs the corresponding fruit names through a loop.

Please note that the array_rand() function only returns randomly selected keys, if you need to get the corresponding values, you will need to use these keys to access the original array.

bannerAds