0


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?

1
  • Why do you not want it to start with 814? You are removing randomness with this. Commented Sep 11, 2012 at 19:47

3 Answers 3

3

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));
Sign up to request clarification or add additional context in comments.

Comments

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

5 Comments

This rules out all numbers starting with a zero. Is that what the OP wants?
@Jon, actually I would prefer to allow zeros too.
if I change it to mt_rand(000000000, 999999999); would that be interpreted as just one zero or require 9 digits still?
I am.... running a for loop using that to echo numbers....still havent gotten one starting with 0 yet. Don't know if its because it's random or it doesnt allow for it. Haha.
Well, the real test would be if all of your random number are 9 digits long. If not, then you can assume that those parameters produce non-9-digit numbers.
-1

Use preg_match func:

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

Or use

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

Or use

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

2 Comments

all slower than substr() or strpos()
It's best to avoid regex functions when regular string comparison functions will work (the former are much slower).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.