MadnessRed Posted November 5, 2008 Share Posted November 5, 2008 Hi I was wondering if there was already a function that did this. For example, Say I have 3 items, 1,2 and 3, and I had an array saying how much of each I had eg. $items = array(1 => 75, 2 => 25, 3 => 0); Then it would pick and random item, so there would be a 75% chance if picking item 1, 25% of picking an item 2 and % chance of picking an item 3. I was wondering if there already was a function for this. if not I can make one myself easy enough. Link to comment https://forums.phpfreaks.com/topic/131539-solved-weighted-rand/ Share on other sites More sharing options...
rhodesa Posted November 5, 2008 Share Posted November 5, 2008 i don't think there is a "weighted random" function like that...off the top of my head though, this should work: <?php $items = array( 1 => 75, 2 => 25, 3 => 0, ); $list = array(); foreach($items as $key => $weight){ if($weight > 0) //Skip if there is no weight $list = array_merge($list,array_fill(0,$weight,$key)); //Add the entry $weight times } shuffle($list); //Randomize list print $list[0]; //Grab one ?> Link to comment https://forums.phpfreaks.com/topic/131539-solved-weighted-rand/#findComment-683186 Share on other sites More sharing options...
MadnessRed Posted November 5, 2008 Author Share Posted November 5, 2008 ok, thanks Link to comment https://forums.phpfreaks.com/topic/131539-solved-weighted-rand/#findComment-683190 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.