[Noisebridge-discuss] PHP sucks [was Re: [drama] New logo source?]

John Adams jna at retina.net
Tue Jan 12 22:37:23 UTC 2010


On Jan 12, 2010, at 2:24 PM, Leif Ryge wrote:
>
> Ok, this was bothering me, so I just went and checked to see how the
> randomizer was implemented. Here it is:

> I have no idea why someone chose to ask for 2 random values when they
> only needed one, but you might expect that this would produce suitably
> random results anyway. And, with an older version of PHP, I believe  
> this
>  code actually would yield an even weighting. And, with a newer
> version, it would pick the first item 2/3 of the time and never pick  
> the
> third at all. And, with our middle-aged version of PHP (5.2.4-2), it
> produces the distribution observed above. Hooray for PHP!
>
> Here is a demo from 5.2.6-3ubuntu4.4:
> $ php5 -r '$a=array(1,2,3); for ($i=1; $i<10000; $i++) { $r =
> array_rand($a, 2); echo "$r[0] $r[1]\n"; }'|sort|uniq -c
>    3398 0 1
>    1641 0 2
>    1641 1 2
>    1666 2 0
>    1653 2 1


In the array_rand function,  each key from the source array has an  
equal chance of being picked, BUT the order that they are returned in  
is not random.

A workaround is to use shuffle($r) afterwards.

  php -r '$a=array(1,2,3); for ($i=1; $i<10000; $i++) { $r = array_rand 
($a, 2); shuffle($r); echo "$r[0] $r[1]\n"; }'|sort | uniq -c
    1569 0 1
    1673 0 2
    1764 1 0
    1631 1 2
    1713 2 0
    1649 2 1

Also, hello Noisebridge! I've lurking here for a bit and not made it  
to a meeting yet.

-john

---
John Adams (@netik)
Retina Communications
jna at retina.net
http://www.retina.net/tech
this email is: [  ] bloggable   [ x ] ask first   [   ] confidential




More information about the Noisebridge-discuss mailing list