Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Trying to return random number 1-5. 1 often, 5 least often

I am trying to set up a random number picker 1 through 5, with each number showing up on a predefined percentage value; 1 showing up often and 5 showing up the least often. So for example, the chances if these 5 numbers showing up might be as follows: 1 – 45%, 2 – 25%, 3 – 15%, 4 – 10%, 5 – 5%. I have tried a few approaches (one seen below I know its totally wrong) with out any luck. Does anyone have any ideas how to efficiently approach this?

$rand = rand(1,1000);

if ($rand <= 275) {
    $rand_num = 1;
} else if ($rand > 275 && $rand <= 525) {
    $rand_num = 2;
} else if ($rand > 525 && $rand <= 750) {
    $rand_num = 3;
} else if ($rand > 750 && $rand <= 925) {
    $rand_num = 4;
} else {
    $rand_num = 5;
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

One of the ways — just use conditions to split the random result:

To keep it simple, set the random numbers to be between 1 and 100

1 – 45%, 2 – 25%, 3 – 15%, 4 – 10%, 5 – 5%.

The code will be:

$rand = rand(1,100);

if ($rand <=45) {
    $rand_num = 1;
}

if ($rand >45 && $rand <=70) {
    $rand_num = 2;
}

if ($rand >70 && $rand <=85) {
    $rand_num = 3;
}

if ($rand >85 && $rand <=95) {
    $rand_num = 4;
}

if ($rand >95) {
    $rand_num = 5;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading