I am trying to figure out how to shuffle an array of URL’s based on a percentage so that each URL get’s picked a certain number of times.
<?php
$urls = array(
'http://www.google.com'=>'25%',
'http://www.yahoo.com'=>'25%',
'http://www.bing.com' =>'50%');
I thought about going the rand() route and just getting a random number between 1-100 and making a switch statement with a bunch of ranges, but that seems less than elegant and clumsy. I also don’t know how reliable doing this would be. I am trying to get as close to perfect as possible. If I shuffle through 100 times I am not sure most of the rand() examples would list the above array with google.com and yahoo.com getting selected 25 times each (+/- 2) and bing.com getting selected 50 times.
Is their a way to get accurate weighted shuffling? Thanks
You’ll still want a rand. In a distribution of 100, you’re not likely to get a perfectly even 100% distribution. If you want that, you’ll need to store state in a DB, or somehow static to the server itself. In fact, what you would do is just decrement the array values until they’re all 0, then start again.
Here is a representation of how it would work without the perfect-match distribution (assuming it is in a function):