PHP Array array_rand() Function (With Examples)

In this tutorial, we will learn about the PHP array_rand() function with its usage, syntax, parameters, return value, and examples. By IncludeHelp Last updated : December 31, 2023

PHP array_rand() Function

The array_rand() function is used to get random keys from an array, it can be used to get single random key or array of the keys by specifying the number of random keys.


The syntax of the array_rand() function:

array_rand(array, [number]);


The parameters of the array_rand() function:

  • array is an input array, we have to get the random keys from it.
  • number is the total number of random keys, it is used to get more than one random key i.e. an array of keys.

Return Value

The return type of this method is int|string|array, it returns the key for a random entry. [Source]

Sample Input/Output

$arr = array("name" => "Amit", "age" => 21, "city" => "Gwalior");
random key: age

PHP array_rand() Function Example

$arr = array("name" => "Amit", "age" => 21, "city" => "Gwalior");
print("random key: " . array_rand($arr) ."\n");

//generating an array of random keys
print("array of random keys...\n");
print_r(array_rand($arr, 2));


The output of the above example is:

random key: age
array of random keys...
    [0] => age 
    [1] => city

To understand the above example, you should have the basic knowledge of the following PHP topics:

All PHP Programs

Comments and Discussions!

Load comments ↻

Copyright © 2024 All rights reserved.