PHP to generate 8-digit numeric number

How to generate an 8-digit positive numeric number (string okay)?

I tried using rand(), but that only goes up to 32768 (not long enough).

Try using PHP: mt_rand - Manual and set a min and max.

mt_rand(10000000, 99999999)
<?php

$digits_needed=8;

$random_number=''; // set up a blank string

$count=0;

while ( $count < $digits_needed ) {
    $random_digit = mt_rand(0, 9);
    
    $random_number .= $random_digit;
    $count++;
}

echo "The random $digits_needed digit number is $random_number";

?>

As the mt_rand() function could potentially return a number of any length, it’s run in a loop, each time generating a different random digit. That digit gets concatenated to the end of the random number string.

echo rand(1000, 9999) . rand(1000, 9999);

I guess… anything bad there?

Cups: Only ‘bad’ thing is that your code is incapable of generating a number below 10001000.
Space’s works fine,
or you could just do


$num = str_pad(mt_rand(1,99999999),8,'0',STR_PAD_LEFT);

and end up with an 8 character string of numbers, zero-padded to the left if the number is less than 10000000

Guess I was a little hasty with the code example I posted. The same sort of thing would happen.

This is over kill, you do not need to do this. I’m just playing around and chose to use a “Cryptographically Secure Pseudo-Random Number Generator" (CSPRNG) cause I can. On most Linux/Unix machines it will use “[URL=“https://secure.wikimedia.org/wikipedia/en/wiki/Urandom”]/dev/urandom” while on Windows machines with PHP 5.3 will use the "[URL=“https://secure.wikimedia.org/wikipedia/en/wiki/CryptGenRandom”]CryptoAPI: CryptGenRandom” method. These of course are stronger then rand or mt_rand but greatly over kill for this. Doing this just for fun.


function bin2int ( $b ) {
  return ( ord( $b[ 0 ] )
       | ( ord( $b[ 1 ] ) << 8 )
       | ( ord( $b[ 2 ] ) << 16 )
       | ( ord( $b[ 3 ] ) << 24 ) );
}

function randnum ( $length )
{
  $o = '';

  do {
    $b  = mcrypt_create_iv( 4, MCRYPT_DEV_URANDOM );
    $o .= str_replace( '-', '', bin2int( $b ) );
  } while ( strlen( $o ) < $length );

  return substr( $o, 0, $length );
}

for ( $i = 0; $i < 100; $i++ )
  echo str_pad( $i, 2, 0, STR_PAD_LEFT ), ": ", randnum( 8 ), "\
";

In most cases when wanting a value with a length of 8 will run at most once though the loop. A value with a length of 32 will on average run 4 times though the loop. And so on.

Ha ha, that’s great. I think I’ll just go with …


mt_rand(10000000, 99999999)

Thanks all.

…probably the best idea, if you permit numbers which are zero padded to the left, they may get parsed as being 0 based hex values somewhere you do not expect it.


echo 00000012;
// 10

ooh good point Cups. Didnt think of that… though technically str_pad will return a -string-… so it should still work as long as you dont try and interpret the value of said string.