DevilishLime Posted October 9, 2012 Share Posted October 9, 2012 Hello there, I was wondering if it would be possible if I could create a random number through rand();. However I want it to be able to have certain numbers have a higher percentage of being picked. Such as the number 10 would have a 20% of being picked, and the number 2 would have a 3% chance of being picked. How would I go about doing this? Any help would be appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/269270-random-numbers-with-percentages/ Share on other sites More sharing options...
Barand Posted October 9, 2012 Share Posted October 9, 2012 $arr = array(10,10,10,10,10,20,30,40,50,60); In the above example, 10 has a 50% chance of being picked with echo $arr[array_rand($arr)]; Quote Link to comment https://forums.phpfreaks.com/topic/269270-random-numbers-with-percentages/#findComment-1384047 Share on other sites More sharing options...
xyph Posted October 9, 2012 Share Posted October 9, 2012 Alternately, <?php $values = array( // Number => Weighted chance 1 => 1, 2 => 1, 3 => 5, // 5x more likely than 1,2 4 => 3 // 3x more likely than 1,2 ); // The total of all the chances $total = array_sum($values); // Will track the sum of all tested chances $i = 0; // The number we're looking to find $find = mt_rand(1,$total); // Loop through value=>chance array foreach( $values as $val => $chance ) { // Add current chance to the running total $i += $chance; // Check if the running total equals or exceeds the number we're trying to find if( $find <= $i ) // If so, break out of the loop break; } // The last assigned value before breaking will contain the number echo $val; ?> The process is more complex, but the input is more simplified. Quote Link to comment https://forums.phpfreaks.com/topic/269270-random-numbers-with-percentages/#findComment-1384063 Share on other sites More sharing options...
DevilishLime Posted October 10, 2012 Author Share Posted October 10, 2012 Thank you both for the reply. I think I will have to take xyph's route, as it looks easier for the use I am wanting it for. However I will need to take some time out to learn the different functions used within the xyph's answer...so I can fully understand it. Much appreciated. Quote Link to comment https://forums.phpfreaks.com/topic/269270-random-numbers-with-percentages/#findComment-1384279 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.