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
Syntax
array_rand(array $array, int $num = 1): int|string|array
Parameters
| Parameter | Description |
|---|---|
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
<?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
<?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
| Version | Change |
|---|---|
| PHP 4.0 | Added |
| PHP 7.1 | Uses the Mt19937 generator, so mt_srand() seeds it. |
Related
shuffle()· Shuffle an array into a random order, in place. Keys are discarded. Not suitable for security-sensitive randomness.- PHP Arrays · tutorial
- PHP Array Functions · tutorial