|  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Request #48010 Returning element value from array_rand()
Submitted: 2009-04-18 03:09 UTC Modified: 2011-04-08 20:32 UTC
Avg. Score:2.7 ± 1.7
Reproduced:4 of 4 (100.0%)
Same Version:2 (50.0%)
Same OS:3 (75.0%)
From: me at 46bit dot com Assigned:
Status: Open Package: Arrays related
PHP Version: 5.3.0RC1 OS: All
Private report: No CVE-ID: None
Have you experienced this issue?
Rate the importance of this bug to you:

 [2009-04-18 03:09 UTC] me at 46bit dot com
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:
$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:
$array = array('a', 'b', 'c');

$values = array_rand($array, 2);

foreach($values as &$value) {
$value = $array[$value];

Expected result:
2 Random values from $array.


Add a Patch

Pull Requests

Add a Pull Request


AllCommentsChangesGit/SVN commitsRelated reports
 [2009-04-18 03:17 UTC]
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.  
 [2011-04-08 20:32 UTC]
-Package: Feature/Change Request +Package: Arrays related
PHP Copyright © 2001-2019 The PHP Group
All rights reserved.
Last updated: Sat Aug 24 17:01:27 2019 UTC