The array_rand
method is used to randomly pick one or more keys of elements of an array.
array_rand(array $array, int $num = 1): int|string|array
The num
arguments denote the number of keys to be picked randomly.
This method returns a single value when we need only one random key. If we choose to have multiple random keys, then an array is returned.
<?php$numbers = ['one' => 1,'two' => 2,'three' => 3,'four' => 4,'five' => 5,'six' => 6];$rand_keys = array_rand($numbers);var_dump($rand_keys);$rand_keys = array_rand($numbers, 3);var_dump($rand_keys);?>
In the code above:
numbers
.array_rand
method to get the single random key from the array.array_rand($numbers);
This method will return the single key as a return value.
array_rand
method to get multiple random keys by calling:array_rand($numbers, 3);
This will return an array with randomly selected element keys.