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));
Output for 7.1.10, 7.2.2
string(1) "m"
Output for 7.2.1
string(1) "h"
Output for 7.2.0
string(1) "p"
Output for 7.1.14
string(1) "n"
Output for 7.1.13
string(1) "w"
Output for 7.1.12
string(1) "k"
Output for 7.1.11
string(1) "v"
Output for 7.1.6 - 7.1.7, 7.1.9
string(1) "u"
Output for 7.1.8
string(1) "c"
Output for 7.1.5
string(1) "b"
Output for 7.1.4
string(1) "q"
Output for 7.1.0 - 7.1.1, 7.1.3
string(1) "i"
Output for 7.1.2
string(1) "x"

preferences:
44.96 ms | 421 KiB | 5 Q