note 126993 added to function.array-rand
| From: | divinity76+spam at gmail dot com | Date: | Tue, 19 Apr 2022 04:08:45 +0000 |
| Subject: | note 126993 added to function.array-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-218295@lists.php.net to get a copy of this message | ||
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)];
}
----
Server IP: 45.112.84.4
Probable Submitter: 80.90.5.135 (proxied: 84.49.158.188)
----
Manual Page -- https://php.net/manual/en/function.array-rand.php
Edit -- https://main.php.net/note/edit/126993
Del: integrated -- https://main.php.net/note/delete/126993/integrated
Del: useless -- https://main.php.net/note/delete/126993/useless
Del: bad code -- https://main.php.net/note/delete/126993/bad+code
Del: spam -- https://main.php.net/note/delete/126993/spam
Del: non-english -- https://main.php.net/note/delete/126993/non-english
Del: in docs -- https://main.php.net/note/delete/126993/in+docs
Del: other reasons-- https://main.php.net/note/delete/126993
Reject -- https://main.php.net/note/reject/126993
Search -- https://main.php.net/manage/user-notes.php