Core\Random\Seeded::pick
Chooses one value from an array with a seeded generator, so the same choices come back on every run.
You make the generator with new Core\Random\Seeded(42). The number 42 is the seed. Two generators with the same seed choose the same values in the same order. This is useful for test data, such as the product in each test order. Every value in the array has the same chance. pick returns the value itself, not its key, and the array does not change. If the array is empty, the result is null.
Good to know: anybody who knows the seed knows every choice. For a choice nobody may predict, use Core\Random::pick.
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
The same seed picks the same values
<?nvs// Shows that two generators with the same seed choose the same values.
array<string> $colors = ['red', 'green', 'blue', 'yellow'];Core\Random\Seeded $first = new Core\Random\Seeded(42);Core\Random\Seeded $second = new Core\Random\Seeded(42);
// Each generator chooses five colors. Both lines are the same.string $line = '';string $again = '';int $i = 0;while ($i < 5) { $line = $line . ($first->pick($colors) ?? 'none') . ' '; $again = $again . ($second->pick($colors) ?? 'none') . ' '; $i = $i + 1;}echo $line, "\n";echo $again, "\n";blue red green green redblue red green green redAn empty array
<?nvs// Shows what `pick` returns when the array is empty.
Core\Random\Seeded $generator = new Core\Random\Seeded(42);
// 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 = $generator->pick($names);echo $winner ?? 'nobody', "\n";nobodyTest orders for a demo shop
<?nvs// Shows how to fill a demo shop with orders that are the same on every run.
// Each order gets a product and a country. The seed is fixed, so a screenshot// or a test of the demo shop shows the same five orders every time.array<string> $products = ['Mug', 'T-shirt', 'Poster', 'Notebook'];array<string> $countries = ['DE', 'FR', 'JP', 'US'];Core\Random\Seeded $generator = new Core\Random\Seeded(2024);int $order = 1;while ($order <= 5) { string $product = $generator->pick($products) ?? 'none'; string $country = $generator->pick($countries) ?? 'none'; echo 'order ', $order, ': ', $product, ' to ', $country, "\n"; $order = $order + 1;}order 1: Poster to DEorder 2: T-shirt to DEorder 3: Notebook to JPorder 4: Mug to JPorder 5: Mug to FR