PHP array_rand() 函数
实例
返回包含随机键名的数组:
<?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
The array_rand() function returns a random key name from the array, or returns an array containing random key names if you specify that the function returns more than one key name.
Description
The array_rand() function randomly selects one or more elements from the array and returns them.
The second parameter is used to determine how many elements to select. If more than one element is selected, return an array containing random key names, otherwise return the key name of the element.
Note:Since PHP 4.2.0, srand() or mt_srand() functions are no longer required to seed the random number generator, which is now automatically completed.
Syntax
array_rand(array,number)
Parameter | Description |
---|---|
array | Required. Specify the array. |
number | Optional. Specify how many random keys to return. |
Technical Details
Return Value: | Return a random key from the array, or return an array containing random keys if you specify that the function returns more than one key name. |
PHP Version: | 4+ |
Update Log: |
Since PHP 4.2.0, the random number generator will automatically seed. Since PHP 5.2.10, the result array of the shuffled key names is no longer shuffled. |
More Examples
Example 1
Return a random key from the array:
<?php $a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); print_r(array_rand($a,1)); ?>
Example 2
Return an array containing random string keys:
<?php $a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); print_r(array_rand($a,2)); ?>