Home>Article>Backend Development> PHP function array_rand() that randomly selects one or more elements from an array and returns the key name
Example
Returns an array containing random key names:
"; echo $a[$random_keys[1]]."
"; echo $a[$random_keys[2]]; ?>
Definition and usage
array_rand() function returns a random key name in the array, or if If the specified function returns more than one key name, an array containing random key names will be returned.
Syntax
array_rand(array,number)
Parameters | Description |
array | Required. Specifies an array. |
number | Optional. Specifies how many random elements to return. |
Technical details
Return value: | Returns a random key name in the array, Or if the specified function returns more than one key name, an array containing random key names is returned. |
PHP Version: | 4+ |
##Update Log: | As of PHP 5.2.10, the resulting array of keys is no longershuffled. Since PHP 4.2.0, the random number generatoris automatically seeded. |
"red","b"=>"green","c"=>"blue","d"=>"yellow"); print_r(array_rand($a,1)); ?>Example 2 Returns an array containing random
stringkey names:
"red","b"=>"green","c"=>"blue","d"=>"yellow"); print_r(array_rand($a,2)); ?>Example:
"Dog","b"=>"Cat","c"=>"Horse"); print_r(array_rand($a,1)); ?>Result:
b
The above is the detailed content of PHP function array_rand() that randomly selects one or more elements from an array and returns the key name. For more information, please follow other related articles on the PHP Chinese website!