how can I make it? some people says can make with mt_rand but I think it doesnt work well PHP: $rand = mt_rand(1,100);if($rand<=10){ $player->getInventory()->addItem(Item::get(264,0,1));} else if($rand<=40){$player->getInventory()->addItem(Item::get(368,0,1));} else if($rand<=50){$player->getInventory()->addItem(Item::get(265,0,1));} I want to make 10%, 40%, 50%
PHP: $rand = mt_rand(1,100);if ($rand <= 10) { // 10% chance $player->getInventory()->addItem(Item::get(264,0,1));} else if($rand <= 50) { // 40% chance $player->getInventory()->addItem(Item::get(368,0,1));} else { // 50% chance $player->getInventory()->addItem(Item::get(265,0,1));}
than it can also over 100? it can? and I need to use just else in last? Code: $rand = mt_rand(1,140); if ($rand <= 10) { // 10% chance $player->getInventory()->addItem(Item::get(264,0,1)); } else if($rand <= 50) { // 40% chance $player->getInventory()->addItem(Item::get(368,0,1)); } else if($rand <= 140){ // 90% chance $player->getInventory()->addItem(Item::get(265,0,1)); }
You can do that but you can replace the last "else if" with just "else" because that if statement will always be true if it ever gets called. Also since you changed the maximum number, the percentages you have are now incorrect. 10/140 * 100 = 7.14% (to 2 d.p) 40/140 * 100 = 28.57% (to 2 d.p) 100/140 * 100 = 71.43% (to 2 d.p)
It's supposed to be <= 40 for 40% chance. The 140? That's going to make your stuff more complicated. mt_rand(1, 100) gives you a number in the range [1, 100]. The probability of the number being <= 30 is 30%. The probability of the number being <= x is x% (x belongs in [1, 100]). If you change the range to [1, 140], the probability changes as well. If you need precision, go for (mt_rand() / mt_getrandmax()) * 100. Something to note: reusing the same probability value changes the probability too.