#43807 [Opn->Bgs]: array_rand doesn't return keys in random order

From: Date: Sat, 12 Jan 2008 15:31:14 +0000
Subject: #43807 [Opn->Bgs]: array_rand doesn't return keys in random order
References: 1  Groups: php.bugs 
Request: Send a blank email to php-bugs+get-121221@lists.php.net to get a copy of this message
 ID:               43807
 Updated by:       tony2001@php.net
 Reported By:      martin dot kober at wu-wien dot ac dot at
-Status:           Open
+Status:           Bogus
 Bug Type:         Arrays related
 Operating System: Linux 2.6
 PHP Version:      5.2.5
 New Comment:

array_rand() uses the same algorithm as shuffle().
And I can't see any problems with both functions.


Previous Comments:
------------------------------------------------------------------------

[2008-01-10 17:55:39] 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";
}




------------------------------------------------------------------------


-- 
Edit this bug report at http://bugs.php.net/?id=43807&edit=1


Thread (2 messages)

« previous php.bugs (#121221) next »