3v4l.org

run code in 300+ PHP versions simultaneously
<?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));

preferences:
36.82 ms | 402 KiB | 5 Q