Skip to content

Instantly share code, notes, and snippets.

@frops
Created October 9, 2019 08:45
Show Gist options
  • Save frops/140e77af173407521aefbde7fc894ab1 to your computer and use it in GitHub Desktop.
Save frops/140e77af173407521aefbde7fc894ab1 to your computer and use it in GitHub Desktop.
PHP: Get random item from array
<?php
function float(float $min, float $max): float
{
$random = \mt_rand() / \mt_getrandmax() * $max;
return \max($random, $min);
}
function getRandomItem(array $array)
{
$sumChance = 0.0000;
$max = 0.0000;
$maxIndex = 0;
$rand = float(0, 100);
foreach ($array as $index => $a) {
if ($a['chance'] > $max) {
$maxIndex = $index;
}
$sumChance += $a['chance'];
if ($rand <= $sumChance) {
return $a;
}
}
return $array[$maxIndex];
}
$array = [
['chance' => 50.15, 'item' => 'item1'],
['chance' => 10.00, 'item' => 'item2'],
['chance' => 6.10, 'item' => 'item3'],
['chance' => 15.34, 'item' => 'item4'],
['chance' => 14.66, 'item' => 'item5'],
['chance' => 0.75, 'item' => 'item6'],
['chance' => 3, 'item' => 'item7'],
];
$res = [];
$c = 0;
while ($c++ < 100) {
$randomValue = getRandomItem($arr)['item'];
if (!isset($res[$randomValue])) {
$res[$randomValue] = 0;
}
$res[$randomValue]++;
}
var_dump($res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment