PHP 8 reference · Array Functions

PHP array_rand() Function

Pick one or more random keys from an array. Use it with the array to get random values; not for security.

PHP 8 Since 4.0

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

array_rand(array $array, int $num = 1): int|string|array

Parameters

ParameterDescription
array The input array.
num optional How many keys to pick. Default: 1

Return value

One key, or an array of num keys in their original order.

Examples

A random valueTry it yourself
<?php
mt_srand(7); // fixed seed so the output is repeatable
$quotes = ["Keep going", "Ship it", "Read the docs"];
echo $quotes[array_rand($quotes)], "\n";

Output

Keep going
Several keysTry it yourself
<?php
mt_srand(3);
$deck = range(1, 10);
print_r(array_rand($deck, 3));

Output

Array
(
    [0] => 6
    [1] => 7
    [2] => 8
)

For anything security-related, such as tokens or draws with prizes, use random_int() or the Random\Randomizer class (PHP 8.2+) instead.

Version history

VersionChange
PHP 4.0Added
PHP 7.1Uses the Mt19937 generator, so mt_srand() seeds it.

Was this page helpful?