array_rand()
function returns the random key name in the array, or if you specify that the function returns more than one key name, it returns an array containing the random key name.
Returns an array containing random key names:
<?php $a = array ( "red" , "green" , "blue" , "yellow" , "brown" ) ; $random_keys = array_rand ( $a , 3 ) ; echo $a [ $random_keys [ 0 ] ] . "<br>" ; echo $a [ $random_keys [ 1 ] ] . "<br>" ; echo $a [ $random_keys [ 2 ] ] ; ?>
Try it yourself
Return a random key from the array:
<?php $a = array ( "a" => "red" , "b" => "green" , "c" => "blue" , "d" => "yellow" ) ; print_r ( array_rand ( $a , 1 ) ) ; ?>
Try it yourself
Returns an array containing random string key names:
<?php $a = array ( "a" => "red" , "b" => "green" , "c" => "blue" , "d" => "yellow" ) ; print_r ( array_rand ( $a , 2 ) ) ; ?>
Try it yourself
array_rand ( array , number )
parameter | describe |
---|---|
array | Required. Specify array. |
number | Optional. Specifies how many random key names are returned. |
array_rand()
function randomly selects one or more elements from the array and returns.
The second parameter is used to determine how many elements to be selected. If more than one element is selected, an array containing random key names is returned, otherwise the key name of that element is returned.
Note: Since PHP 4.2.0, it is no longer necessary to use the srand()
or mt_srand()
function to seed the random number generator, and it has been automatically completed.