Return an array containing random keys:
<?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 ] ] ; ?>The array_rand() function returns a random key in an array, or an array containing random keys if the specified function returns more than one key.
array_rand( array,number )
parameter | describe |
---|---|
array | Required. Specifies an array. |
number | Optional. Specifies how many random elements to return. |
Return value: | Returns a random key in an array, or an array containing random keys if the specified function returns more than one key. |
---|---|
PHP version: | 4+ |
Update log: | As of PHP 5.2.10, the resulting array of keys is no longer shuffled. As of PHP 4.2.0, the random number generator is automatically seeded. |
Return a random key in the array:
<?php$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");print_r(array_rand($ a,1));?>Return an array containing random string keys:
<?php$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");print_r(array_rand($ a,2));?>