Jump to content

Random digits


graham23s

Recommended Posts

Hi Guys,

 

i use this simple math to get a random 9 digits appended to my string:

 

$uniqueID = rand(000000000, 999999999);

$uniID    = "FCP-$uniqueID";

 

but sometimes the random digit doesn't use all 9 characters e.g

 

FCP-123456789

 

then some might be:

 

FCP-12345678

 

i'm trying to consistantly make the random number 9 characters long, is there a way i can make sure the numeric number is 9 digits long and no less?

 

thanks for any help guys

 

Graham

Link to comment
https://forums.phpfreaks.com/topic/142378-random-digits/
Share on other sites

You can pad the number with leading zeros, or use this:

 

$uniqueID = rand(100000000, 999999999);

 

or, you could do this:

 

<?php
$rand_num = null;

// so we loop until the length of rand_num is either 9 or more.
while(strlen($rand_num) >= 9){
   $rand_num .= rand(0,9); // oops, forgot a DOT (to append to the string rather than overwrite it)
}

echo($rand_num); // see the result
?>

Link to comment
https://forums.phpfreaks.com/topic/142378-random-digits/#findComment-745995
Share on other sites

rand only calculates and returns a unsigned 32 bit integer so your number range is too high.  To work around this, you can instead do something like this:

 

$uniID = "FCP-";
for ($x = 0; $x < 10; $x++) {
   $uniID .= rand(0,9);
}

 

Note that this does not guarantee a unique id though.  You will still have to check it against previously generated id numbers.  If you want some kind of random number generation that does not depend on checking previously generated numbers, you can incorporate the current time into it, since the time will always be unique, compared to previous timestamps. 

Link to comment
https://forums.phpfreaks.com/topic/142378-random-digits/#findComment-745998
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.