Skip to content
Tutorials Center
My learning

Topics

PHP Reference ยท Array Functions

PHP array_rand() function

Reference for PHP array_rand(): pick one or several random keys from an array, order of the result, errors for empty arrays and why it is not for secrets.

array_rand() picks one or more random keys from an array. It returns keys, not values, so you look up the value yourself with $array[$key]. With the default of one pick it returns a single key; with $num greater than one it returns an array of keys.

The random numbers come from the Mersenne Twister generator, which is fine for games, samples and shuffling a menu, but not for tokens, passwords or anything an attacker should not guess.

PHP
<?php
$colors = ["red", "green", "blue"];
$key = array_rand($colors);
echo $colors[$key];   // one of the three

Try it

PHP Picking a random element

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

PHP Errors and reproducible picks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

Syntax

PHP
array_rand(array $array, int $num = 1): int|string|array
Name Description
$array A non-empty array to pick from.
$num How many keys to pick, from 1 to count($array). Default 1.

Return value: a single key when $num is 1; otherwise an array of $num distinct keys.

Errors: throws ValueError if the array is empty or $num is out of range (less than 1 or greater than the array size).

Usage notes

  • You get keys, not values. Use $array[array_rand($array)] for the value.
  • The order of multiple keys follows the original array, not the order they were picked. Call shuffle() on the result if you want random order.
  • No repeats within one call. For picks with replacement, call array_rand($array) in a loop.
  • Not cryptographically secure. Use random_int() to choose an index when secrecy matters.
  • Seeding: mt_srand() makes results repeatable, but the exact sequence may differ between PHP versions, so never store expectations about it.
  • Large arrays: picking one key is cheap, but for lists you can also use $list[random_int(0, count($list) - 1)].