数组 函数
PHP Manual

array_rand

(PHP 4, PHP 5)

array_rand 从数组中随机取出一个或多个单元

说明

mixed array_rand ( array $input [, int $num_req ] )

array_rand() 在你想从数组中取出一个或多个随机的单元时相当有用。它接受 input 作为输入数组和一个可选的参数 num_req,指明了你想取出多少个单元 - 如果没有指定,默认为 1。

如果你只取出一个, array_rand() 返回一个随机单元的键名,否则就返回一个包含随机键名的数组。这样你就可以随机从数组中取出键名和值。

Example #1 array_rand() 例子

<?php
srand
((float) microtime() * 10000000);
$input = array("Neo""Morpheus""Trinity""Cypher""Tank");
$rand_keys array_rand($input2);
print 
$input[$rand_keys[0]] . "\n";
print 
$input[$rand_keys[1]] . "\n";
?>

参见 shuffle()

参数

input

The input array.

num_req

Specifies how many entries you want to pick. Trying to pick more elements than there are in the array will result in an E_WARNING level error.

返回值

If you are picking only one entry, array_rand() returns the key for a random entry. Otherwise, it returns an array of keys for the random entries. This is done so that you can pick random keys as well as values out of the array.

更新日志

版本 说明
5.2.10 The resulting array of keys is no longer shuffled.
4.2.0随机数发生器自动进行播种。

范例

Example #2 array_rand() example

<?php
$input 
= array("Neo""Morpheus""Trinity""Cypher""Tank");
$rand_keys array_rand($input2);
echo 
$input[$rand_keys[0]] . "\n";
echo 
$input[$rand_keys[1]] . "\n";
?>

参见


数组 函数
PHP Manual