Winning percentage in PHP

Asked

Viewed 153 times

-1

Hello, I am creating a system of items on my website. Each item has a certain chance to win.

For example, 0.01%

I would like to know how to make PHP every time the user plays, try to win some item with this percentage.

Kind of:

if(drop_item(0.01) == true) {
    echo "Você ganhou uma poção!";
} else {
    echo "Você não ganhou nada!";
}

If you know how to do this with multiple items, with each item with a chance to win, I would be very happy :)

Thank you for your attention.

1 answer

1


You can use the function rand() passing a minimum and maximum value:

echo mt_rand(1, 10000); // Mostra um número entre 1 e 10000, por exemplo, 2634

If I’m not mistaken 0.01% is 1 chance every 10000, then:

if(mt_rand(1, 10000) === 1) {
    echo "Você ganhou uma poção!";
} else {
    echo "Você não ganhou nada!";
}

You can do a function that takes that percentage and converts:

function sortear($porcentagem) {
    return mt_rand(1, 100 / $porcentagem) === 1;
}

if(sortear(0.01)) {
    echo "Você ganhou uma poção!";
} else {
    echo "Você não ganhou nada!";
}

The function already returns true or false

  • I understood, but how can I make this percentage conversion to number (which in this case was 10000)?

  • In case you need to pass a number in % and return the maximum value?

  • I think so, yeah. I am storing the items in an array, and in this array I would like to put the chance value of winning in % for a better visualization, in case I need to change something later.

  • I edited the answer, I believe it’s more or less what you need

  • You missed 0, and I also missed that it’s division and not multiplication

  • Now just returning that person won XD

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.