Dan
Dan

Reputation: 31

PHP Choose Array Item Percentage of The Time?

I am trying to figure out a way to have a particular array item chosen a certain percentage of the time. So lets say:

$testArray = array('item1', 'item2', 'item3', 'item4', 'item5');

Now how would I go about having item1 chosen lets say 40% of the time. I know this is probably really easy but I can't seem to wrap my head around it today.

Upvotes: 2

Views: 188

Answers (1)

Fabian Schmengler
Fabian Schmengler

Reputation: 24576

With these percentages:

$chances = array(40,15,15,15,15);

Choose a random number between 1 and 100:

$rand = rand(1,100);

And select the according array item:

| item1              | item2  | item3  | item4  | item5  |
0                   40       55       70       85       100
$ref = 0;
foreach ($chances as $key => $chance) {
    $ref += $chance;
    if ($rand <= $ref) {
        return $testArray[$key];
    }
}

Possible improvement for a more general solution:

  • use array_sum() instead 100
  • assure that $chances has the same keys as the input array (i.e. with array_keys and array_combine)

Upvotes: 3

Related Questions