-1

So I'm building a small script that will "randomly" choose an array key, but based on the weight of the value of the key, my array looks like this:

array:2 [
  1 => "10"
  2 => "20"
]

So in this case key 1 would have 33.33% chance and key 2 would have 66.66% to be chosen. How would I go about doing this?

Klaus
  • 399
  • 1
  • 5
  • 17
  • What have you tried so far? – wayneOS Jul 02 '21 at 07:23
  • 1
    Check this out: [Random value from array by weight in php](https://stackoverflow.com/questions/12571578/random-value-from-array-by-weight-in-php) – Harriete Jul 02 '21 at 07:24
  • Please provide more information. I am not sure how you came up with 33.33% from 2 values. It should be a 50% chance right? – DevTurtle Jul 02 '21 at 07:25
  • Or this one: [Generating random results by weight in PHP](https://stackoverflow.com/questions/445235/generating-random-results-by-weight-in-php) – Code4R7 Jul 02 '21 at 07:25

1 Answers1

0

You could do something like this, where you use an intermediary array with the keys repeated a number of time corresponding to their weight, and then randomly picking an item from this intermediary array.

$weighted = [1=>"10", 2=>"20"];

$intermediary = [];
foreach ($weighted as $key=>$weight) {
    $intermediary = array_merge($intermediary, array_fill(0, $weight, $key));
}

$item = $intermediary[array_rand($intermediary)];
David
  • 1,898
  • 2
  • 14
  • 32
  • 1
    You forgot ' " ' after 20 line 1. And you need to replace the 2 $weighted by $intermediary in the foreach. – Basto Jul 02 '21 at 08:28