Example
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]]; ?>
Definition and usage
array_rand() function returns a random key name in the array, or if If the specified function returns more than one key name, an array containing random key names will be returned.
Syntax
array_rand(array,number)
Parameters | Description |
array | Required. Specifies an array. |
number | Optional. Specifies how many random elements to return. |
Technical details
Return value: | Returns a random key name in the array, Or if the specified function returns more than one key name, an array containing random key names is returned. |
PHP Version: | 4+ |
##Update Log : | As of PHP 5.2.10, the resulting array of keys is no longershuffled. Since PHP 4.2.0, the random number generator is automatically seeded. |
<?php $a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); print_r(array_rand($a,1)); ?>
string key names:
<?php $a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); print_r(array_rand($a,2)); ?>
<?php $a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse"); print_r(array_rand($a,1)); ?>
b
The above is the detailed content of PHP function array_rand() that randomly selects one or more elements from an array and returns the key name. For more information, please follow other related articles on the PHP Chinese website!