Req #48010 [Opn->Sus]: Returning element value from array_rand()

From: Date: Sun, 01 Mar 2020 23:13:02 +0000
Subject: Req #48010 [Opn->Sus]: Returning element value from array_rand()
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-225828@lists.php.net to get a copy of this message
Edit report at https://bugs.php.net/bug.php?id=48010&edit=1 ID: 48010 Updated by: cmb@php.net Reported by: me at 46bit dot com Summary: Returning element value from array_rand() -Status: Open +Status: Suspended Type: Feature/Change Request Package: Arrays related Operating System: All PHP Version: 5.3.0RC1 Block user comment: N Private report: N New Comment: This feature looks controversial (at least regarding the boolean parameter) and as such needs discussion, for which this bug tracker is not appropriate. Please bring that forward on the internals mailing list[1]. Thanks! [1] <https://www.php.net/mailing-lists.php#internals> Previous Comments: ------------------------------------------------------------------------ [2009-04-18 03:17:33] rasmus@php.net A very common thing to do is to unset the random element from the array so you never pick the same one twice. In order to do that you have to return the index of the element. Returning the value is useless. And since it is trivial to go from index to value, that seemed like the logical way to implement this. ------------------------------------------------------------------------ [2009-04-18 03:09:02] me at 46bit dot com Description: ------------ With array_rand() as it is now, it only returns the key of the element(s) it picks randomly from the array. The problem with this is that much/most of the time all the programmer wants is to get a random value from that array - not the key. At present you then have to do code such as $arrayName[array_rand($arrayName)] or a foreach loop when getting multiple random elements. Whilst of limited importance, this could quite be implemented via the addition of a boolean parameter on the end of array_rand without too much trouble. Reproduce code: --------------- <?php $array = array('a', 'b', 'c'); $values = array_rand($array, 2, TRUE); // return the value if TRUE, the key if FALSE (FALSE the default in order to mirror current functionality) ?> Would be desired to get 2 random values from $array, as opposed having to do: <?php $array = array('a', 'b', 'c'); $values = array_rand($array, 2); foreach($values as &$value) { $value = $array[$value]; } ?> Expected result: ---------------- 2 Random values from $array. ------------------------------------------------------------------------ -- Edit this bug report at https://bugs.php.net/bug.php?id=48010&edit=1

« previous php.bugs (#225828) next »