The array_rand Function
The array_rand
function returns a random
key from an array. The first parameter is the
array, and the second optional parameter
specifies how many random keys to return.
If it is not specified - one key is returned,
and if specified - the given number of keys
is returned as an array.
Syntax
array_rand(array $array, int $num = 1): int|string|array
Example
In this example, the function will return a random key from the array:
<?php
$arr = ['a'=>1, 'b'=>2, 'c'=>3, 'd'=>4, 'e'=>5];
echo array_rand($arr);
?>
Code execution result:
'c'
Example
Let's return a random element from the array, knowing the random key:
<?php
$arr = ['a'=>1, 'b'=>2, 'c'=>3, 'd'=>4, 'e'=>5];
$key = array_rand($arr);
echo $arr[$key];
?>
Code execution result:
3
Example
Let's set the second parameter to the value
3
- in this case, the function will return an array
of 3
random keys (3 keys -
since the second parameter is 3):
<?php
$arr = ['a'=>1, 'b'=>2, 'c'=>3, 'd'=>4, 'e'=>5];
$keys = array_rand($arr, 3);
var_dump($keys);
?>
Code execution result:
['a', 'b', 'e']