note 126997 added to function.array-rand

From: Date: Tue, 19 Apr 2022 13:36:16 +0000
Subject: note 126997 added to function.array-rand
Groups: php.notes 
Request: Send a blank email to php-notes+get-218297@lists.php.net to get a copy of this message
for a cryptographically secure version, try <?php /** * fetch a random key from array, using a cryptograpically secure rng * discussed+reviewed at https://codereview.stackexchange.com/questions/275832/cryptographically-secure-version-of-the-core-array-rand-function/ * * @param array $array * @throws ValueError if array is empty * @return int|string key */ 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'], ["PEAN"=>0], [] ]; foreach ($tests as $test) { echo array_rand_cryptographically_secure($test) . "\n"; } ?> (this is an improved version, which unlike the first version, avoids copying *all* the keys) ---- Server IP: 45.112.84.4 Probable Submitter: 80.90.5.135 (proxied: 81.166.215.112) ---- Manual Page -- https://php.net/manual/en/function.array-rand.php Edit -- https://main.php.net/note/edit/126997 Del: integrated -- https://main.php.net/note/delete/126997/integrated Del: useless -- https://main.php.net/note/delete/126997/useless Del: bad code -- https://main.php.net/note/delete/126997/bad+code Del: spam -- https://main.php.net/note/delete/126997/spam Del: non-english -- https://main.php.net/note/delete/126997/non-english Del: in docs -- https://main.php.net/note/delete/126997/in+docs Del: other reasons-- https://main.php.net/note/delete/126997 Reject -- https://main.php.net/note/reject/126997 Search -- https://main.php.net/manage/user-notes.php

« previous php.notes (#218297) next »