Jump to content

Generating 9 random digits exactly


graham23s

Recommended Posts

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

Link to comment
https://forums.phpfreaks.com/topic/190694-generating-9-random-digits-exactly/
Share on other sites

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?

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;
}
?>

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.