php.net |  support |  documentation |  report a bug |  advanced search |  search howto |  statistics |  random bug |  login
Bug #43807 array_rand doesn't return keys in random order
Submitted: 2008-01-10 17:55 UTC Modified: 2008-01-12 15:31 UTC
From: martin dot kober at wu-wien dot ac dot at Assigned:
Status: Not a bug Package: Arrays related
PHP Version: 5.2.5 OS: Linux 2.6
Private report: No CVE-ID: None
Welcome back! If you're the original bug submitter, here's where you can edit the bug or add additional notes.
If you forgot your password, you can retrieve your password here.
Password:
Status:
Package:
Bug Type:
Summary:
From: martin dot kober at wu-wien dot ac dot at
New email:
PHP Version: OS:

 

 [2008-01-10 17:55 UTC] martin dot kober at wu-wien dot ac dot at
Description:
------------
The keys that array_rand returns are uniformly distributed, but their order is not:

Counting the 0, 1 and 2 of the sample code output, I consistently get some distribution like this:

Overall count (this is fine):
  0   1   2 
649 694 657 

Count per position (this is wrong):
      0   1   2 
[0] 500 181 319 
[1] 149 513 338 
0 is way too often in [0] (same for 1 in [1]), there must be some problem with the algorithm. 

Adding a shuffle() is a workaround, but this is a potential trap for users depending on an even distribution.

There are some similar bugs in the DB, but they are all very old and seem to be Windows-related.

Reproduce code:
---------------
for ($i = 1; $i <= 1000; $i++) {
echo implode(" ", array_rand(array(1,2,3), 2)), "<br>\n";
}



Patches

Pull Requests

History

AllCommentsChangesGit/SVN commitsRelated reports
 [2008-01-12 15:31 UTC] tony2001@php.net
array_rand() uses the same algorithm as shuffle().
And I can't see any problems with both functions.
 
PHP Copyright © 2001-2025 The PHP Group
All rights reserved.
Last updated: Tue Jul 29 18:00:03 2025 UTC