In this tutorial, you shall learn about PHP array_rand() function which can get us a random key from an array, with syntax and examples.

PHP array_rand() Function

The PHP array_rand() function returns a random key from an array. Or you can tell array_rand() to return a specific number of keys taken from an array randomly. In case array_rand() returns multiple keys, it returns them as array.

Syntax of array_rand()

The syntax of array_rand() function is

array_rand( array, number)

where

ParameterDescription
array[mandatory] Array from which keys are picked randomly.
number[optional] Number of keys the function has to return. The default value is 1.

Function Return Value

array_rand() returns a random key from an array. The function returns an indexed array of random keys if you specify an argument for the parameter number.

ADVERTISEMENT

Examples

1. Get a random key from the array

In this example, we will take an associative array with key-value pairs. We will call array_rand() function with this array passed as argument for the parameter array. We are not passing any argument for parameter number. Only one key would be returned by the function, since the default value for parameter number is 1.

PHP Program

<?php
$array1 = array("a"=>21, "b"=>54, "m"=>35, "k"=>66);
$key = array_rand($array1);
echo $key;
?>

Output

PHP array_rand() - Get Random Key from Array

2. Get array of random keys from Array

In this example, we will take an associative array with key-value pairs. We will call array_rand() function to return 3 keys picked randomly from the array.

PHP Program

<?php
$array1 = array("a"=>21, "b"=>54, "m"=>35, "k"=>66);
$number = 3;
$keys = array_rand($array1, $number);
print_r($keys);
?>

Output

array_rand() returns keys of the original array as values in indexed array.

PHP array_rand() - Get Array of Random Keys from Array

You can access the individual keys using index.

Conclusion

In this PHP Tutorial, we learned how to , using PHP Array array_rand() function.