Friday, August 3, 2007

Code to generate Unique Random Numbers - PHP

I was looking for a Unique Random Number with different length to use it for one of the calling card company. This PHP script just rocks. Enjoy, download the code from svn rather than copy and paste.

#!/usr/bin/php

function generateuniquenumbers($len,$count,$includezero=1)
{

if( strlen($count) > $len )
{
echo "Looks something funny in the parameter which you have supplied. \n";
return ;
}
echo "Generating " . $count . " numbers with length " . $len . "\n";
$mult = 0;
$fract = 0;
$numbers[] = "";
mt_srand(10);
if( $len > 9 )
{
$mult = (int)($len/9);
$fract = (int) $len % 9;
} else {
$fract = $len;
}
if( $fract > 0 )
{
$minfract = "";
$maxfract = "";
for($m=0; $m<$fract; $m++)
{
if($includezero)
$minfract = "0";
else
$minfract .= "1";
$maxfract .= "9";
}
}

for($numcount=0;$numcount<$count;$numcount++)
{
$curnumber = "";
for($i=0;$i<$mult;$i++)
{
if( $includezero )
$currand = mt_rand(0,999999999);
else
$currand = mt_rand(111111111,999999999);
if( strlen($currand) <>
{
$templen = strlen($currand);
for( $pad = 9 - $templen; $pad > 0; $pad--)
$curnumber .= "0";
}
$curnumber .= $currand;
}
if( $fract > 0 )
{
$currand = mt_rand($minfract,$maxfract);
if( strlen($currand) <>
{
$templen = strlen($currand);
for( $pad=strlen($maxfract)-$templen;$pad > 0;$pad--)
$curnumber .= "0";
}
$curnumber .= $currand;
}
if( !in_array($curnumber,$numbers) )
{
$numbers[] = $curnumber;
}
else
$numcount --;
}
return $numbers;
}

$ncount = 20;
$nlength = 20;

$numbers = generateuniquenumbers($nlength,$ncount,0);

for($k=1;$k<=$ncount;$k++)
echo $numbers[$k] . "\n";

?>

Here is the output:

[root@kansdevhost devel]# ./kansrand.php
Generating 20 numbers with length 20
16181070355240094632
35133279664046683582
56683089348828603637
61797018627269033641
32242637617039241045
53775119541769589123
98009706424319286130
67830750255154478737
4554441961805820434
24613857566557562252
86485415760605734578
30890354240158234429
12549747923000041677
85786735955666425870
44706552566779852177
41866325246584913132
61537972143640201927
52078343311552209047
53657534152010051142
74283518264934633688

You can download using svn with the following command,

svn co http://codeoftheday.googlecode.com/svn/trunk/03Aug2007

Do Let me know if there are any improvements done, will keep updated.

Enjoy.

No comments: