Current Location: Home> Function Categories> array_rand

array_rand

Randomly fetch one or more units from an array
Name:array_rand
Category:Array
Programming Language:php
One-line Description:Returns one or more random keys in the array.

Definition and usage

array_rand() function returns the random key name in the array, or if you specify that the function returns more than one key name, it returns an array containing the random key name.

Example

Example 1

Returns 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 ] ] ;
?>

Try it yourself

Example 2

Return a random key from the array:

 <?php
$a = array ( "a" => "red" , "b" => "green" , "c" => "blue" , ​​"d" => "yellow" ) ;
print_r ( array_rand ( $a , 1 ) ) ;
?>

Try it yourself

Example 3

Returns an array containing random string key names:

 <?php
$a = array ( "a" => "red" , "b" => "green" , "c" => "blue" , ​​"d" => "yellow" ) ;
print_r ( array_rand ( $a , 2 ) ) ;
?>

Try it yourself

grammar

 array_rand ( array , number )
parameter describe
array Required. Specify array.
number Optional. Specifies how many random key names are returned.

illustrate

array_rand() function randomly selects one or more elements from the array and returns.

The second parameter is used to determine how many elements to be selected. If more than one element is selected, an array containing random key names is returned, otherwise the key name of that element is returned.

Note: Since PHP 4.2.0, it is no longer necessary to use the srand() or mt_srand() function to seed the random number generator, and it has been automatically completed.

Similar Functions
Popular Articles