note 74406 added to function.array-rand
| From: | ReinoudElhorst at osu1 dot php dot net | Date: | Tue, 10 Apr 2007 10:50:33 +0000 |
| Subject: | note 74406 added to function.array-rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-125259@lists.php.net to get a copy of this message | ||
Please note that (at least in PHP 4.3.11), while each key from the source array has a equal chance
of being picked, the order in which they are returned is NOT random. In an array with keys from one
to 10, where 2 random keys are picked, 0 is picked as the first number 18.8% of the time, and only
as second number in 1.1% of the time:
$n=100000;
$a=array(1,2,3,4,5,6,7,8,9,10);
$b=array();
for($i=0;$i<sizeof($a);$i++) {
$b[$i]=array(0,0);
}
for($i=0;$i<$n;$i++) {
$keys=array_rand($a,2);
$b[$keys[0]][0]++;
$b[$keys[1]][1]++;
}
for ($i=0;$i<sizeof($b);$i++){
printf("%d: %04.1f%% %04.1f%% %04.1f%%", $i,
($b[$i][0]/$n*100),($b[$i][1]/$n*100),($b[$i][0]+$b[$i][1])/$n*100);
}
The result is:
0: 18.8% 01.1% 19.9%
1: 17.0% 03.3% 20.3%
2: 14.3% 05.7% 20.0%
3: 12.2% 07.9% 20.1%
4: 10.0% 10.0% 20.0%
5: 07.8% 12.0% 19.8%
6: 05.5% 14.5% 20.0%
7: 03.3% 16.6% 19.9%
8: 01.2% 18.9% 20.1%
9: 10.0% 09.9% 19.9%
The workaround is adding a shuffle command to shuffle the keys:
0: 10.0% 10.0% 20.0%
1: 10.0% 10.0% 20.0%
2: 10.0% 10.0% 20.0%
3: 10.0% 10.0% 20.0%
4: 10.0% 10.0% 20.0%
5: 10.0% 10.0% 20.0%
6: 10.1% 10.0% 20.1%
7: 10.0% 10.0% 20.0%
8: 10.0% 10.0% 20.0%
9: 10.0% 10.0% 20.0%
----
Server IP: 83.137.20.120
Probable Submitter: 82.204.44.50
----
Manual Page -- http://www.php.net/manual/en/function.array-rand.php
Edit -- https://master.php.net/note/edit/74406
Del: integrated -- https://master.php.net/note/delete/74406/integrated
Del: useless -- https://master.php.net/note/delete/74406/useless
Del: bad code -- https://master.php.net/note/delete/74406/bad+code
Del: spam -- https://master.php.net/note/delete/74406/spam
Del: non-english -- https://master.php.net/note/delete/74406/non-english
Del: in docs -- https://master.php.net/note/delete/74406/in+docs
Del: other reasons-- https://master.php.net/note/delete/74406
Reject -- https://master.php.net/note/reject/74406
Search -- https://master.php.net/manage/user-notes.php