Skip to content

Instantly share code, notes, and snippets.

@savvot
Last active March 9, 2017 14:15
Show Gist options
  • Save savvot/f8eae60ba8f2fda50a78 to your computer and use it in GitHub Desktop.
Save savvot/f8eae60ba8f2fda50a78 to your computer and use it in GitHub Desktop.
Weighted random function
<?php
/**
* @param array $data array of "key => weight" data to get random key from, all weights must be positive integers
* @return mixed key from $data array choosen by weighted random
*/
function weightRandom(array $data)
{
$c = count($data);
if (!$c) {
return false;
} elseif ($c == 1) {
return key($data);
}
$weight = rand(1, array_sum($data));
foreach ($data as $k => $w) {
$weight -= $w;
if ($weight <= 0) {
return $k;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment