PHP: Get a Random Element from Array, Biased
This is a function that fetches a random element from an array. However, it’s not like array_rand(), because you can bias the results so that some elements have a better chance of being picked. This is done by having an associated array with the elements to be fetched as keys and the relative probability as the values.
$items = array( 'A' => 3, 'B' => 1, 'C' => 1, ); function getRandElement( $array ) { $tot_prob = array_sum( $array ); foreach ( $array as $element => $element_prob ) { if ( mt_rand( 1, $tot_prob ) <= $element_prob ) { return $element; } else { $tot_prob -= $element_prob; } } return 0; } echo getRandElement( $items );
This code has a 60% chance of echoing an A, 20% chance for B and 20% for C.us aa loansfinance about banking loans scams businessabout low fee loan paydayaccount savings cash loanday loan saving pay accountpay account savings using day loanday saving account loan paybad credit actual loan company Map

Sorry for stupid question, I am just a newb
What is “-=”, what happens in this line:
$tot_prob -= $element_prob;
Thanks in advance, very nice wrriten function!
Comment by Ka82 — April 3, 2007 @ 8:57 pm
Ka82:
a -= bis a shortcut fora = a - b. I.e. the code could also have been written like this:$tot_prob = $tot_prob - $element_prob;Note that this is works for most operators, so you can also write
+=,*=,/=and.=. The latter is very useful when handling strings. This syntax exists in most languages.Comment by Tim — April 4, 2007 @ 12:44 pm
Thanks for your answer Tim,
Could you please give me one more tip? :)
I doesn’t undesrstood your algoritm completely…
walking throug array with foreach is OK, but “return 0;” will return 1st element of archive, not the element with high weight, is it ok? It seems it will be working uncorrectly with
$items = array(
‘A’ => 1,
‘B’ => 1,
‘C’ => 3,
);
Comment by Ka82 — April 5, 2007 @ 11:35 am
Ka82, actually, the last
returnstatement is unnecessary. It should never be executed; it is just there in case I hade written anything wrong, so that the function still would return something. Also, it wouldn’t return element 0: it would just return the integer 0, which means that the function failed.As to why that part of the code never gets executed, if you try to follow the code flow, you will se that the
ifstatement will always be true for the last element, and when it is true, the function ends because it reaches anotherreturn.$tot_probwill always equal$elemnt_probfor the last element.Hope it helps.
Comment by Tim — April 5, 2007 @ 12:22 pm
Thanks a lot!
Comment by Ka82 — April 7, 2007 @ 2:44 am
You don’t need to call mt_rand every iteration — just call it once at the top.
Comment by Jesse — February 7, 2008 @ 10:35 pm
Jesse: I don’t quite understand how that would work. Could you please supply an example?
Comment by Tim — June 19, 2008 @ 10:17 am