<?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');
}
return key(array_slice($array, random_int(0, $max), 1, true));
}
$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";
}
- Output for 8.1.5
- 0
b
0
- Output for 8.1.4
- 1
c
0
- Output for 8.1.3
- 1
b
4
- Output for 8.1.2
- 1
a
9
- Output for 8.1.1
- 0
a
9
- Output for 8.0.12, 8.0.18, 8.1.0
- 2
c
4
- Output for 8.0.2, 8.0.11, 8.0.17
- 2
b
0
- Output for 8.0.13, 8.0.16
- 2
b
9
- Output for 8.0.15
- 0
a
4
- Output for 8.0.10, 8.0.14
- 1
b
9
- Output for 8.0.9
- 0
b
4
- Output for 8.0.8
- 1
c
4
- Output for 8.0.1, 8.0.7
- 2
a
4
- Output for 8.0.6
- 0
c
9
- Output for 8.0.5
- 2
b
4
- Output for 8.0.3
- 0
c
4
- Output for 7.4.0 - 7.4.29
- Parse error: syntax error, unexpected '|', expecting '{' in /in/UHAfJ on line 3
Process exited with code 255.
preferences:
49.87 ms | 427 KiB | 5 Q