PHP Tutorial - PHP array_rand() function






Definition

The array_rand() function returns one or more random values from an array.

array_rand() leaves the original array intact.

Syntax

PHP array_rand() function has the following syntax.

mixed array_rand ( array arr [, int amount] )

Parameter

ParameterIs RequiredDescription
arrayRequired.Get random value from array
numberOptional.How many random keys to return

Example

Get random values from an array


<?php/*from   w ww  . j a va 2s  .c o m*/
    $names = array("A", "B", "C", "D","java2s.com");
    $two_names = array_rand($names, 2);
    print_r($two_names);
    print "\n";
    
    $a=array("a"=>"A","b"=>"B","c"=>"C","j"=>"java2s.com");
    print_r(array_rand($a,1));
    print "\n";
    print_r(array_rand($a,2));
    
?>

The code above generates the following result.