The array_rand() function returns a random key from an array, or it returns an array of random keys if you specify that the function should return more than one key.
Returns a random key from an array, or an array of random keys if you specify that the function should return more than one key
Parameter | Description |
---|---|
array | Required. Specifies an array |
number | Optional. Specifies how many random keys to return |
Syntax
array_rand(array,number)
Example
$array = array("Samuel","Cooper","Lachlan","James","Prince");
$random_keys=array_rand($array,3);
echo $array[$random_keys[0]]."<br>";
echo $array[$random_keys[1]]."<br>";
echo $array[$random_keys[2]];
Output random so, does not fix
Samuel
James
Prince
More Example (Return a random key from an array)
$array=array("a"=>"Samuel","b"=>"Cooper","c"=>"Lachlan","d"=>"James");
print_r(array_rand($array,1));
Output random so, does not fix
c
More Example (Return an array of random string keys)
$array=array("a"=>"Samuel","b"=>"Cooper","c"=>"Lachlan","d"=>"James");
print_r(array_rand($array,2));
Output random so, does not fix
Array ( [0] => b [1] => c )