PHP Function Reference

PHP array_rand() Function



The PHP array_rand() function picks one or more random entries out of an array, and returns the key (or keys) of the random entries. It uses a pseudo random number generator to pick the entries.

Syntax

array_rand(array, num)

Parameters

array Required. Specify the input array.
num Optional. Specify the number of entries to be picked. Default is 1.

Return Value

When picking only one entry, key for a random entry is returned. Otherwise, an array of keys for the random entries is returned.

Exceptions

Throws E_WARNING level error when tried to pick more elements than there are in the array, and NULL will be returned.

Example:

In the example below, array_rand() function is used to pick random entries from a given array.

<?php
$Arr = array(10, 20, 30, 40, 50, 60, 70, 80);

//picking single entry
$x = array_rand($Arr);
//picking multiple entries
$y = array_rand($Arr, 3);

//using keys to display its value
//in the original array
echo "Arr[x] = ".$Arr[$x]."\n";
echo "Arr[y[0]] = ".$Arr[$y[0]]."\n";
echo "Arr[y[1]] = ".$Arr[$y[1]]."\n";
echo "Arr[y[2]] = ".$Arr[$y[2]]."\n";
?>

The output of the above code will be:

Arr[x] = 10
Arr[y[0]] = 10
Arr[y[1]] = 40
Arr[y[2]] = 80

Example:

Consider one more example where the array_rand() function is used with an associative array.

<?php
$Arr = array("Marry"=>"London", 
             "John"=>"Paris", 
             "Jo"=>"Hong Kong", 
             "Kim"=>"Amsterdam", 
             "Adam"=>"Tokyo");

//picking single entry
$x = array_rand($Arr);
//picking multiple entries
$y = array_rand($Arr, 3);

//using keys to display its value
//in the original array
echo "Arr[x] = ".$Arr[$x]."\n";
echo "Arr[y[0]] = ".$Arr[$y[0]]."\n";
echo "Arr[y[1]] = ".$Arr[$y[1]]."\n";
echo "Arr[y[2]] = ".$Arr[$y[2]]."\n";
?>

The output of the above code will be:

Arr[x] = Paris
Arr[y[0]] = London
Arr[y[1]] = Paris
Arr[y[2]] = Amsterdam

❮ PHP Array Reference