Malik Drako Malik Drako - 1 year ago 83
PHP Question

Generating random values with restricted digits

What is the best way to generate a random integer with a restricted set of digits?

I want to generate a 4 digit random number, where each digit is in the range [1..6]. I was thinking generate a number in the range [0..1295], then converting to base 6 and incrementing the digits, but that goes through a string.

Answer Source

Without string conversion, and with only one call to a random number generator, you could do this:

function myRandom() {
    $num = mt_rand(0, 1295);
    $result = 0;
    for ($i = 0; $i < 4; $i++) {
        $result = $result*10 + $num % 6;
        $num = floor($num / 6);
    return $result + 1111;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download