livethedead Posted May 8, 2012 Share Posted May 8, 2012 This isn't for anything practical, I'm just fiddling. Anyways, I'm wondering if there's anyway to make this more efficient since at higher lengths it could become really heavy. $l is length of the number. function fixed_random($l) { $number = ""; do { $r = mt_rand(0, $l); $number .= $r; } while (strlen($number) < $l); return $number; } Quote Link to comment https://forums.phpfreaks.com/topic/262252-fixed-length-random-number/ Share on other sites More sharing options...
Jessica Posted May 8, 2012 Share Posted May 8, 2012 <?php function fixed_random($digits) { $range_start = pow(10, $digits-1); // $digits=1, $range_start=0, 2:10, 3:100 .... $range_end = pow(10, $digits)-1; // $digits=1, $range_end=9, 2:99, 3: 999 .... $number = mt_rand($range_start, $range_end); return $number; ?> Not tested, just my first thought. Quote Link to comment https://forums.phpfreaks.com/topic/262252-fixed-length-random-number/#findComment-1343961 Share on other sites More sharing options...
trq Posted May 8, 2012 Share Posted May 8, 2012 Quite easy. Say you want a random number that must have a length of 5. Given that information, we know that it must be between 10000 and 99999, so: mt_rand(10000, 99999); Done. Quote Link to comment https://forums.phpfreaks.com/topic/262252-fixed-length-random-number/#findComment-1343964 Share on other sites More sharing options...
livethedead Posted May 8, 2012 Author Share Posted May 8, 2012 Hahaha oh dear /facepalm. Quote Link to comment https://forums.phpfreaks.com/topic/262252-fixed-length-random-number/#findComment-1343967 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.