CKTIS / PHP
array_rand()
Select keys at random from a nonempty array.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
array_rand(array $array, int $num = 1): int|string|arraySelect keys at random from a nonempty array. Requesting one key returns a single key; requesting several returns an array of distinct keys in their original order. Use the returned keys to read the actual values. A count outside the allowed range raises a value error.
Signature
array_rand(array $array, int $num = 1): int|string|array
Example output
[true,["a","b"]]
Examples
<?php
$bins = ['a'=>4,'b'=>7];
$one = array_rand($bins);
echo json_encode([array_key_exists($one, $bins), array_rand($bins, 2)]);
Result
[true,["a","b"]]