This simple library will help you pick a random item through a collection of items (string, objects, ints, whatever), by optionally giving them a weight.
use BenTools\Picker\Picker;
require_once __DIR__ . '/vendor/autoload.php';
$collection = [
[
'foo',
80,
],
[
'bar',
60,
],
[
'baz',
5,
],
];
$picker = Picker::create();
foreach ($collection as $key => [$value, $weight]) {
$picker = $picker->withItem($value, $weight);
}
echo $picker->pick(); // Will be mostly foo or bar
Of course you can also simply pick a random value with a simple, no-weighted set:
$picker = Picker::create()->withItems(['foo', 'bar', 'baz']);
echo $picker->pick(); // Will be a truly random value between foo, bar and baz
The picker can optionally shift items once they're picked:
$picker = Picker::create(shift: true)->withItems(['foo', 'bar']);
$picker->pick(); // let's assume `foo` is picked
$picker->pick(); // only `bar` remains
$picker->pick(); // RuntimeException
This library requires PHP 7.3+.
composer require bentools/picker
./vendor/bin/pest