Home > Software design >  Lower probability of getting a specific number in random_int() PHP
Lower probability of getting a specific number in random_int() PHP

Time:09-12

I have this code that generates a number from 0 to 6, and depending on the number an echo is displayed.

I would like to know if there is a way to make it hard to get "1" and obviously the echo "correct" hard to get.

Should I just increment the number in random_int()?

$code = random_int(0, 6);

if ($code == 1) {
    echo json_encode($correct);
    return false;
}
if ($code == 2) {
    echo json_encode($bad);
    return false;
}
if ($code == 3) {
    echo json_encode($error);
    return false;
}
if ($code == 4) {
    echo json_encode($bad);
    return false;
}
if ($code == 5) {
    echo json_encode($error);
    return false;
}
if ($code == 6) {
    echo json_encode($bad);
    return false;
}

CodePudding user response:

First off: better change to $code = random_int(1, 6); , otherwise $code can be 0 but there is no code to handle this.

Yes you could increment the number in random_int(), and then make the "correct" less likely.

There are many other ways to do it. One of the ways:

add another random statement (executed only when first random returns 1)

Hence add

if ($code==1) {$code = random_int(1, 6);}

after the line

$code = random_int(1, 6);

Note: If you want to do it further, add more lines, such as

if ($code==1) {$code = random_int(1, 6);}
if ($code==1) {$code = random_int(1, 6);}
if ($code==1) {$code = random_int(1, 6);}
  •  Tags:  
  • php
  • Related