This inbuilt function of PHP is used to fetch a random number of elements from an array. The element is a key and can return one or more than one key. On a practical basis, this is not that useful because the function uses pseudo-random number generator that is not suitable for cryptographic purposes.
Syntax:
array_rand($array, $num)
Parameters: The function takes only two arguments and are described below:
- $array (mandatory): This is a mandatory parameter and refers to the original input array.
- $num (optional): This parameter refers to the number of random numbers needed to be returned. This has to be greater than or equal to one otherwise E_WARNING is thrown along.
Return Value: This function returns the random generated values from the array. The number of returned elements depends on the value of the $num, assigned to the function.
Examples:
Input :
$array = ("ram"=>"20", "krishna"=>"42", "aakash"=>"15")
$num = 2
Output :
Array
(
[0] => ram
[1] => aakash
)
Input :
$array = ("ram"=>"20", "krishna"=>"42", "aakash"=>"15")
Output : krishna
Below programs illustrates the array_rand() function in PHP:
Reference:
http://php.net/manual/en/function.array-rand.php
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
20 Jun, 2023
Like Article
Save Article