bentools / picker
Helps you pick a random item with weight management.
Installs: 9 284
Dependents: 0
Suggesters: 0
Security: 0
Stars: 3
Watchers: 3
Forks: 2
Open Issues: 1
Requires
- php: >=7.3
Requires (Dev)
- pestphp/pest: ^1.0
- squizlabs/php_codesniffer: @stable
- symfony/var-dumper: ^5.0
README
Picker
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.
Usage
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
Shift
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
Installation
This library requires PHP 7.3+.
composer require bentools/picker
Tests
./vendor/bin/pest