PHP array_rand() Function

PHP array_rand() Function

The array_rand() function in PHP picks one or more random keys out of an array.

Syntax

array_rand ( array $array [, int $num = 1 ] )

Parameter

array(required)- This parameter represents the input array.

num(optional)- This parameter specifies how many entries should be picked. The default value is 1.

Return

This function returns the key for a random entry if only one entry is picked else it returns an array of keys for the random entries.

It returns NULL or an E_WARNING level error is you pick more elements than there are in the array.

Example 1

"Orange","2"=>"Blueberry","3"=>"Plum","4"=>"Guava");
 //will return a random key
 echo("The random key is ");
 print_r(array_rand($array,1));
 ?> 

Output

The random key is 2

Example 2

"Orange","2"=>"Blueberry","3"=>"Plum","4"=>"Guava");
 //passing num as 3
 $num=3;
 //will return list of random keys
 echo("The random keys are "); 
 print_r(array_rand($array, $num));
 ?> 

Output

The random keys are Array
 (
     [0] => 1
     [1] => 3
     [2] => 4
 ) 

Example 3

"Orange","2"=>"Blueberry","3"=>"Plum","4"=>"Guava");
 //passing num as 7 i.e. more than the size of array
 $num=7;
 echo("The random keys are ");
 //will return list of random keys 
 print_r(array_rand($array,$num));//will return error
 ?> 

Output

PHP Warning:  array_rand(): Second argument has to be between 1 and the number of elements in the array in /workspace/Main.php on line 8