bentools/picker

Helps you pick a random item with weight management.

1.0.1 2017-10-04 15:58 UTC

README

Latest Stable Version License Build Status Coverage Status Quality Score Total Downloads

Picker

Let's say you have a collection of objects / values / things / whatever.

You want to pick a random value, but with a weight management.

Here it is.

Usage

use BenTools\Picker\Picker;

require_once __DIR__ . '/vendor/autoload.php';

$collection = [
    [
        'value'  => 'foo',
        'weight' => 80,
    ],
    [
        'value'  => 'bar',
        'weight' => 60,
    ],
    [
        'value'  => 'baz',
        'weight' => 5,
    ],
];

$picker = Picker::create();
foreach ($collection as $key => $value) {
    $picker = $picker->withItem($key, $value['value'], $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

Installation

This library requires PHP 5.6+.

composer require bentools/picker

Tests

./vendor/bin/phpunit

See also

bentools/split-test-analyzer

bentools/cartesian-product

bentools/pager