Get random element from an array with weights

Expects associative array in a format: ['A' => 1, 'B' => 5] where 1 and 5 are weights of A and B elements. Read more.

php
fork add to bundle source
function get_random_by_weight($weighted_list) { $rand = mt_rand(1, array_sum($weighted_list)); foreach ($weighted_list as $key => $value) { $rand -= $value; if ($rand <= 0) { return $key; } } }

usage

load_function('get_random_by_weight'); $list = [ 'A' => 1, 'B' => 5, 'C' => 90 // this would be the most popular element returned by function ]; $key = get_random_by_weight($list); echo $key; // ...
← how to use this in app?
create log ...inout