3v4l.org

run code in 200+ php & hhvm versions
Bugs & Features
<?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.0.12, 7.1.10, 7.2.2
string(1) "m"
Output for 7.0.27, 7.2.1
string(1) "h"
Output for 7.0.0, 7.0.2, 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.0.14, 7.0.16, 7.1.12
string(1) "k"
Output for 7.0.5, 7.0.9, 7.1.11
string(1) "v"
Output for 7.0.11, 7.1.6 - 7.1.7, 7.1.9
string(1) "u"
Output for 7.0.15, 7.1.8
string(1) "c"
Output for 7.0.19, 7.1.5
string(1) "b"
Output for hhvm-3.18.5, 7.0.6, 7.0.23, 7.0.25, 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"
Output for 7.0.7, 7.0.18, 7.0.26
string(1) "e"
Output for 7.0.24
string(1) "o"
Output for 7.0.22
string(1) "g"
Output for 7.0.20 - 7.0.21
string(1) "z"
Output for hhvm-3.22.0, 7.0.17
string(1) "t"
Output for 7.0.13
string(1) "j"
Output for hhvm-3.21.3, 7.0.1, 7.0.10
string(1) "a"
Output for 7.0.8
string(1) "s"
Output for 7.0.3 - 7.0.4
string(1) "y"
Output for 5.6.0 - 5.6.30
Fatal error: Default value for parameters with a class type hint can only be NULL in /in/qg7ie on line 3
Process exited with code 255.