The array_rand()
function returns one or more random values from an array.
array_rand()
leaves the original array intact.
PHP array_rand() function has the following syntax.
mixed array_rand ( array arr [, int amount] )
Parameter | Is Required | Description |
---|---|---|
array | Required. | Get random value from array |
number | Optional. | How many random keys to return |
Get random values from an array
<?php/*from w ww . j a va 2s .c o 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.