- var_dump: documentation ( source)
- array_reduce: documentation ( source)
- str_split: documentation ( source)
- rand: documentation ( source)
<?php
function array_pick(array $array, bool $weighted = false)
{
$weight = function($value, int $weight = 1){
$item = new class($value, $weight){
public function __construct($value, int $weight){
$this->value = $value;
$this->weight = $weight;
}
};
return $item;
};
foreach($array as $key => $value){
if($weighted){
$items[] = $weight($key, $value);
} else {
$items[] = $weight($value);
}
}
$max = array_reduce($items, function($c, $i){
$c += $i->weight;
return $c;
});
$rand = rand(1, $max);
foreach($items as $item) {
$rand -= $item->weight;
if ($rand <= 0) {
return $item->value;
}
}
}
$array = str_split('qwertyuiopasdfghjklzxcvbnm');
var_dump(array_pick($array));