PHP array_rand() Function
Example
Return an array containing 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]]; ?>
Definition and Usage
The array_rand() function returns a random key name from the array, or returns an array containing random key names if the function is specified to return more than one key name.
Description
The array_rand() function randomly selects one or more elements from the array and returns them.
The second parameter is used to determine how many elements to select. If more than one element is selected, an array containing random key names is returned, otherwise, the key name of the element is returned.
Note:Starting from PHP 4.2.0, srand() or mt_srand() functions are no longer required to seed the random number generator, which is now automatically completed.
Syntax
array_rand(array,number)
Parameter | Description |
---|---|
array | Required. Specify the array. |
number | Optional. Specify how many random key names to return. |
Technical Details
Return Value: | Return a random key from the array, or return an array containing random keys if the function is specified to return more than one key name. |
PHP Version: | 4+ |
Update Log: |
Starting from PHP 4.2.0, the random number generator will be automatically seeded. Starting from PHP 5.2.10, the result array of shuffled key names is no longer generated. |
More Examples
Example 1
Return a random key from the array:
<?php $a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); print_r(array_rand($a,1)); ?>
Example 2
Return an array containing random string keys:
<?php $a=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow"); print_r(array_rand($a,2)); ?>