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/*w  w  w  . j  av  a2  s . co  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.





















Home »
  PHP Tutorial »
    Function reference »




PHP Array Functions
PHP Calendar Functions
PHP Class Functions
PHP Data Type Functions
PHP Date Functions
PHP File Functions
PHP Image Functions
PHP Math Functions
PHP MySQLi Functions
PHP SimpleXML Functions
PHP String Functions
PHP XML Functions
PHP Zip Functions