graham23s Posted January 25, 2009 Share Posted January 25, 2009 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 Quote Link to comment https://forums.phpfreaks.com/topic/142378-random-digits/ Share on other sites More sharing options...
uniflare Posted January 25, 2009 Share Posted January 25, 2009 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 ?> Quote Link to comment https://forums.phpfreaks.com/topic/142378-random-digits/#findComment-745995 Share on other sites More sharing options...
.josh Posted January 25, 2009 Share Posted January 25, 2009 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. Quote Link to comment https://forums.phpfreaks.com/topic/142378-random-digits/#findComment-745998 Share on other sites More sharing options...
graham23s Posted January 25, 2009 Author Share Posted January 25, 2009 ah perfect, thanks guys Graham Quote Link to comment https://forums.phpfreaks.com/topic/142378-random-digits/#findComment-746004 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.