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
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
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
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.