Home >>PHP Array Functions >PHP array_rand() Function
PHP array_rand() Function is used to return a random key from an array or in simple terms it returns an array of the random keys in case the programmer specifies that the function should return more than one key.
Syntax:
array_rand(array, number)
Parameter | Description |
---|---|
array | This is generally used to specify an array in the code, it is a mandatory parameter |
number | This parameter is generally used to specify how many random keys are to be returned. It is usually optional. |
Here, is an example of array_rand() Function in PHP:
<html> <body> <?php $g=array("gautam","abhi","aman","anand","sunil"); $random_keys=array_rand($g,4); echo $g[$random_keys[0]]."<br>"; echo $g[$random_keys[1]]."<br>"; echo $g[$random_keys[2]]."<br>"; echo $g[$random_keys[3]]; ?> </body> </html>
gautam abhi aman anand
Example 2:
<html> <body> <?php $aray = array("gautam"=>"400", "ankur"=>"900", "ashish"=>"770"); $nm = 3; print_r(array_rand($aray, $nm)); ?> </body> </html
Array ( [0] => gautam [1] => ankur [2] => ashish )