3v4l.org

run code in 300+ PHP versions simultaneously
<?php function array_rand_cryptographically_secure(array $array): int|string { $max = count($array) - 1; if ($max < 0) { throw new ValueError ('Argument #1 ($array) cannot be empty'); } if (function_exists('array_is_list') && array_is_list($array)) { // optimization, this avoids creating a copy of all the keys return random_int(0, $max); } return array_keys($array)[random_int(0, $max)]; } $tests = [ [5, 6, 7], ['a' => 1, 'b' => 2, 'c' => 3], ['zero', 4 => 'four', 9 => 'nine'] ]; foreach ($tests as $test) { echo array_rand_cryptographically_secure($test) . "\n"; }

preferences:
34.32 ms | 402 KiB | 5 Q