Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

array_rand

Returns a random key of an array.

Syntax

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

Parameters

ParameterTypeDescription
$arrayarrayThe source array.
$numintOptional. How many keys to return.

Return value

int|string|arrayA single key, or an array of keys.

Examples

A random element — different on every run:

<?php
 
$colors = ['red', 'green', 'blue'];
 
echo $colors[array_rand($colors)];

The function returns a key, not a value:

<?php
 
$colors = ['red', 'green', 'blue'];
 
var_dump(is_int(array_rand($colors)));

Output:

bool(true)

Notes

For draws and anything where unpredictability matters use random_int(): $items[random_int(0, count($items) - 1)].

See also

  • shuffle — Shuffles the elements of an array into a random order.
  • random_int — Returns a random integer from a range.

Related recipes

In the tutorial

  • Arrays — Lists and associative arrays in PHP — creating, changing, iterating and useful functions.

Thanks for reading!

Donate to the site — we work hard for you.