Core\Random::pick
Core\Random::pick(array<T> $a): ?TCore\Random::pick( array<T> $a, ): ?T
Chooses one value from an array at random, for example a tip of the day or a server to connect to.
Every value in the array has the same chance to be chosen. Core\Random::pick returns the value itself, not its key, and the array does not change. If the array is empty, the result is null. Because of that, the result type is nullable, and you check for null before you use it. The choice comes from a cryptographic random generator, so nobody can predict it.
Good to know: when you need more than one value and no value twice, use Core\Random::sample.
Parameters
$aarray<T>The array to choose from.
Return value
Returns ?T. The value of one entry. When $a is empty, the result is null. With an array<?T>, you cannot tell this apart from an entry that is null.
Examples
A tip of the day
<?nvs// Shows how to choose one tip at random from a list.
array<string> $tips = ['Save often.', 'Use short names.', 'Write a test first.'];
// `Core\Random::pick` returns one of the values, or `null` for an empty array.?string $tip = Core\Random::pick($tips);
// The tip changes on every run, so this prints only what is always true: `yes`.if ($tip != null) { echo Core\Arr::contains($tips, $tip) ? 'yes' : 'no', "\n";}
// The array itself does not change. This prints 3.echo Core\Arr::count($tips), "\n";yes3An empty array
<?nvs// Shows what `Core\Random::pick` returns when the array is empty.
// No names were entered, so the list is empty.array<string> $names = [];
// There is nothing to choose, so the result is `null`. This prints `nobody`.?string $winner = Core\Random::pick($names);echo $winner ?? 'nobody', "\n";nobodySpread requests over servers
<?nvs// Shows how to spread requests over several servers by choosing one at random each time.
array<string> $servers = ['10.0.0.1', '10.0.0.2', '10.0.0.3'];array<int> $used = ['10.0.0.1' => 0, '10.0.0.2' => 0, '10.0.0.3' => 0];
// This loop sends 3000 requests. Each one goes to a server chosen at random.int $i = 0;while ($i < 3000) { ?string $server = Core\Random::pick($servers); if ($server != null) { $used[$server] = $used[$server] + 1; } $i = $i + 1;}
// Each server gets about 1000 requests. This prints `true` three times.foreach ($used as string $address => int $count) { echo $count > 800 && $count < 1200 ? 'true' : 'false', "\n";}truetruetrue