PHP array_rand() function
Definition
The array_rand()
function returns one or more random values from an array.
array_rand()
leaves the original array intact.
Syntax
PHP array_rand() function has the following syntax.
mixed array_rand ( array arr [, int amount] )
Parameter
Parameter | Is Required | Description |
---|---|---|
array | Required. | Get random value from array |
number | Optional. | How many random keys to return |
Example
Get random values from an array
<?php/*w w w . j av a2 s . co m*/
$names = array("A", "B", "C", "D","java2s.com");
$two_names = array_rand($names, 2);
print_r($two_names);
print "\n";
$a=array("a"=>"A","b"=>"B","c"=>"C","j"=>"java2s.com");
print_r(array_rand($a,1));
print "\n";
print_r(array_rand($a,2));
?>
The code above generates the following result.