Home>Article>Backend Development> PHP function array_rand() that randomly selects one or more elements from an array and returns the key name

PHP function array_rand() that randomly selects one or more elements from an array and returns the key name

黄舟
黄舟 Original
2017-11-08 13:33:06 2793browse

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

As of PHP 5.2.10, the resulting array of keys is no longer
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:shuffled.
Since PHP 4.2.0, the random number
generatoris automatically seeded.
More examples

Example 1

Return a random key name in the array:

"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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn