What is the array_rand method PHP?

The array_rand method is used to randomly pick one or more keys of elements of an array.

Syntax

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.

Example

<?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:

  • We created an array called numbers.
  • We used the 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.

  • We again used the array_rand method to get multiple random keys by calling:
array_rand($numbers, 3);

This will return an array with randomly selected element keys.

Free Resources