I want a cryptographically secure version of array_rand()
. Is this it?
/**
* retrieve a random key from an array, using a cryptographically secure rng.
* - it does the same as array_rand(), except that this one use a cryptographically secure rng.
* - relatively speaking, it should be significantly slower and more memory hungry than array_rand(), because it is creating a copy of all the keys of the array..
*
* @param array $arr
* @throws ValueError if array is empty
* @return mixed
*/
function array_rand_cryptographically_secure(array $array) {
if (count ( $array ) < 1) {
throw new ValueError ( 'Argument #1 ($array) cannot be empty' );
}
if (PHP_MAJOR_VERSION >= 8 && array_is_list ( $array )) {
// optimization, this avoids creating a copy of all the keys
return random_int ( 0, count ( $array ) - 1 );
}
$keys = array_keys ( $array );
return $keys [random_int ( 0, count ( $keys ) - 1 )];
}
Significant edit: I figured I can use array_is_list()
to avoid copying the keys when given a list.