array_rand
Picks one or more random keys from an array without repeating a key in the same call.
array_rand(array $array, int $num = 1): int|string|array- Added in PHP 4.0
Parameters
| Parameter | Type | Description |
|---|---|---|
$array | array | The array to pick from. Must not be empty. |
$numoptional | int= 1 | How many keys to pick. Must be at least 1 and no larger than the array size. |
Return value
int|string|arrayA single key when num is 1, otherwise an array of keys in the order they appear in the source array.
Errors
Throws a ValueError if the array is empty, or if num is less than 1 or greater than the number of elements.
Changelog
- PHP 8.0.0Throws a ValueError when the array is empty or num is out of range. Previously an E_WARNING was raised and null returned.
- PHP 7.1.0The internal randomisation uses Mt19937 (Mersenne Twister) instead of the platform's libc rand, so seeded results differ from PHP 7.0 and earlier.
array_rand() returns random keys, not values. That is the single most common misreading of this function: to get the value you still have to index back into the array.
The return type changes with num
With $num = 1 — the default — you get a bare key back, an int or a string. With $num of 2 or more you get an array of keys. Code that passes a computed count must handle both shapes, because a count that happens to be 1 does not return a one-element array.
Order and repetition
Keys are picked without replacement, so you never get the same key twice from one call. The returned keys come back in the order they appear in the source array, not in random order — if you want a shuffled selection, run shuffle() on the result or shuffle a copy of the array and slice it.
When to reach for it
Use it for picking a random featured item, drawing a sample of rows, or choosing a random quote — anything where a slight bias is harmless. It is not cryptographically secure: it draws from the shared global Mt19937 engine. For tokens, passwords, giveaways or anything an attacker benefits from predicting, use random_int() against array_keys(), or Random\Randomizer with Random\Engine\Secure.
Example
When to use it
- Pick a random quote or tip to show on a dashboard
- Draw a sample of rows from a dataset for a spot check
- Choose three random related articles to display under a post
- Select a random placeholder avatar for a seeded test user
Frequently asked questions
Does array_rand return keys or values?
It returns keys. To get the value, index back into the array with the returned key, or map over the returned key list.
Is array_rand cryptographically secure?
No. It draws from the shared global Mt19937 engine, which is predictable given enough observed output. Use random_int() with array_keys(), or Random\Randomizer with Random\Engine\Secure, for anything security-sensitive.
How do I get random values in random order?
array_rand returns keys in the array's original order, so shuffle() the returned key list before mapping it to values. Alternatively, shuffle a copy of the array and take array_slice() of the first n elements.
More examples
num = 1 returns a key, not an array
Both single-pick forms return an int, while asking for two returns an array. Code that does foreach over the result breaks when the requested count is 1, so wrap it with (array) or branch on the count.
<?php
mt_srand(7);
$deck = range(10, 50, 10);
var_dump(array_rand($deck)); // int key
var_dump(array_rand($deck, 1)); // still a bare int key
var_dump(array_rand($deck, 2)); // array of two keysGetting a genuinely shuffled sample
The keys from array_rand come out in the array's own order, so the first print_r shows an ascending list. Shuffling the key list afterwards gives a sample that is random in both membership and order.
<?php
mt_srand(3);
$items = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'];
$keys = array_rand($items, 3);
print_r($keys); // ascending: original order
shuffle($keys);
print_r(array_map(fn($k) => $items[$k], $keys));Out-of-range num throws
Asking for more keys than exist, or picking from an empty array, throws a ValueError on PHP 8. Before PHP 8 both cases only warned and returned null, which often turned into a confusing null-index error further down.
<?php
$small = ['x', 'y'];
try {
array_rand($small, 5);
} catch (ValueError $e) {
echo 'ValueError: ', $e->getMessage(), "\n";
}
try {
array_rand([]);
} catch (ValueError $e) {
echo 'ValueError: ', $e->getMessage(), "\n";
}
Discussion