Latest web development tutorials

PHP array_rand () function

PHP Array Reference Complete PHP Array Reference

Examples

It returns an array containing the 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]];
?>

Running instance »

Definition and Usage

array_rand () function returns an array of random keys, or if the specified function returns the name of more than one key, it returns an array containing the random key name.


grammar

array_rand( array,number )

参数 描述
array 必需。规定数组。
number 可选。规定返回多少个随机的元素。

technical details

return value: Returns a random array of keys, or if the specified function returns the name of more than one key, it returns an array containing the random key name.
PHP version: 4+
Update log: Since PHP 5.2.10 onwards, the results of an array of keys is no longer ay of keys is no longer shuffled.

As of PHP 4.2.0, the random number generator is automatically seeded.


More examples

Example 1

Returns a random array of keys:

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
print_r(array_rand($a,1));
?>

Running instance »

Example 2

It returns an array containing a random string of key names:

<?php
$a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
print_r(array_rand($a,2));
?>

Running instance »


PHP Array Reference Complete PHP Array Reference