chriscct7
chriscct7

Reputation: 527

PHP generate random number without a certain prefix?


I want to generate a random 9 character long integer.
I also want to make sure the first 3 digits aren't 814.
This is what I came up with so far:

Function to generate number:

public function randnum(){
$random = substr(number_format(time() * rand(),0,'',''),0,9);
return $random
}


Where I want to get the number at.

$random;
while ((substr(randnum(),0,3)) == '814'){
$random=substr(randnum(),0,3));
}

Is this the right way to ensure the number I get does not start with 814?

Upvotes: 0

Views: 824

Answers (3)

theunraveler
theunraveler

Reputation: 3284

do {
    $random = mt_rand(100000000, 999999999);
} while (strpos($random, '814') === 0);

Upvotes: 2

MrSil
MrSil

Reputation: 618

Use preg_match func:

preg_match("/[^814]/", $str);

Or use

str_replace("814", "", $str);

Or use

preg_replace("/^814/", "", $str);

Upvotes: -1

Jon
Jon

Reputation: 437336

It's a reasonable way to get a number that does not start with 814, but not a reasonable way to get a random number. You shouldn't get time() involved at all, and you should use mt_rand instead of rand.

You could do it better like this:

do {
    $random = sprintf("%09d", mt_rand(0, 999999999));
} while (substr($random, 0, 3) == "814");

If you don't care about the distribution of the generated random numbers (i.e. you are OK with the number being just unpredictable and not really random) and you are going to be generating lots of these, it might make sense to optimize a little:

do {
    $random = sprintf("%03d", mt_rand(0, 999));
} while $random == "814";

$random = $random.sprintf("%06d", mt_rand(0, 999999));

Upvotes: 3

Related Questions