graham23s Posted February 2, 2010 Share Posted February 2, 2010 Hi Guys, I'm trying to generate 9 random digits, i have done rand(0, 999999999) but i was wanting the script to generate 9 random digits exactly not 8 or 7 but consistantly 9 i cant think of a way to dfo ity lol any help would be great thanks guys Graham Quote Link to comment Share on other sites More sharing options...
aeroswat Posted February 2, 2010 Share Posted February 2, 2010 Hi Guys, I'm trying to generate 9 random digits, i have done rand(0, 999999999) but i was wanting the script to generate 9 random digits exactly not 8 or 7 but consistantly 9 i cant think of a way to dfo ity lol any help would be great thanks guys Graham Why not generate each one seperately then add them to a string and convert that string if you need to do math functions on it? Quote Link to comment Share on other sites More sharing options...
wildteen88 Posted February 2, 2010 Share Posted February 2, 2010 Use rand within a for loop. $length = 9; $numb = null; for($i = 0; $i < $length; $i++) { $numb .= rand(0,9); } echo $numb; Quote Link to comment Share on other sites More sharing options...
Psycho Posted February 2, 2010 Share Posted February 2, 2010 This should be a little more efficient: $randNum = sprintf("%09s", rand(0, 999999999)); Quote Link to comment Share on other sites More sharing options...
roopurt18 Posted February 2, 2010 Share Posted February 2, 2010 And another way! <?php echo randdigits( 9 ) . "\n"; echo randdigits( 9 ) . "\n"; echo randdigits( 9 ) . "\n"; echo randdigits( 9 ) . "\n"; echo randdigits( 9 ) . "\n"; echo randdigits( 9 ) . "\n"; echo randdigits( 9 ) . "\n"; echo randdigits( 9 ) . "\n"; /** * Generates $n random digits * * @param int $n */ function randdigits( $n ) { if( ! is_int( $n ) || $n < 1 ) return false; $v = 0; for( $i = 0; $i < $n; $i += 1 ) { $v = ($v * 10) + rand(0,9); } return $v; } ?> Quote Link to comment Share on other sites More sharing options...
akitchin Posted February 2, 2010 Share Posted February 2, 2010 or: rand(100000000, 999999999); Quote Link to comment Share on other sites More sharing options...
Psycho Posted February 2, 2010 Share Posted February 2, 2010 or: rand(100000000, 999999999); But that excludes some valid possibilities, e.g. 001001001. however, that may or may not be an issue for the OP. Quote Link to comment Share on other sites More sharing options...
akitchin Posted February 2, 2010 Share Posted February 2, 2010 ah, yes. good point. Quote Link to comment 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.