note 126993 deleted from function.array-rand by cmb
| From: | cmb@php.net | Date: | Tue, 19 Apr 2022 13:52:06 +0000 |
| Subject: | note 126993 deleted from function.array-rand by cmb | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-218298@lists.php.net to get a copy of this message | ||
Note Submitter: divinity76+spam at gmail dot com
----
for a cryptographically secure version (reviewed at https://codereview.stackexchange.com/questions/275832/cryptographically-secure-version-of-the-core-array-rand-function
), try
<?php
/**
* 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)/*: 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)];
}