0

How to get random value from array set an value in array that will be one to selected more than other?

array('00','01','02');

I want to select an random value from this array with most selected value be '00', i.e the '00' value will be selected 80% and other two values will be 20%.

Here array can have many values, its only an example with three values

1
  • You could use mt_rand to produce a random number between say 0 and 100, then if ($random < 80) {$yourarray[0], or something - maybe a switch statement. That'd probably work. I won't bother posting as an answer. Commented Jan 15, 2012 at 4:18

4 Answers 4

2
$main_array=array('00','01','02');

$priority=array(0,0,0,0,0,0,0,0,1,2);

$rand_index=array_rand($priority);//select a random index from priority array.. $priority[$rand_index] will give you index 0 or 1 or 2 with your priority set..

echo $main_array[$priority[$rand_index]];

I think the code is self explanatory...

Array will have many elements case will come when lets say the requirement will come like 3% probability of "00" 28% prob. of "01" rest to other elements...In that case use array_fill function to fill elements in masses...and array_merge them

Like for the same case I've taken answer will be

$main_array=array('00','01','02');
$priority1=array_fill(0,69,2);
$priority2=array_fill(0,28,1);
$priority3=array_fill(0,3,0);    
$priority=array_merge($priority1,$priority2,$priority3);

$rand_index=array_rand($priority);

echo $main_array[$priority[$rand_index]];
Sign up to request clarification or add additional context in comments.

Comments

0

Here's an idea.

$arr = array('00', '01', '02');
$randInt = rand(1, 10);

if ($randInt <= 8) {
    $value = $arr[0];
}
else if ($randInt == 9) {
    $value = $arr[1];
}
else { // ($randInt == 10)
    $value = $arr[2];
}

There is now an 80% chance that $value contains '00', a 10% chance that it contains '01', and a 10% chance it contains '02'. This may not be the most efficient solution, but it will work.

Comments

0

one of many options

$a = array_fill(0, 8, '0');
$a['9']='1';
$a['10']='2';

echo $a[array_rand($a,1)];

Comments

0

Use a parallel array with the probability distribution, e.g.:

array('80', '10', '10');

Use standard random number function to generate a number between 0 and 99, then look it up in this array. The index you find it at is then used as the index to the values array.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.