NYCPHP Meetup

NYPHP.org

[nycphp-talk] generate random unique 8-digit number

Michael B Allen ioplex at gmail.com
Wed Mar 11 02:25:35 EDT 2009


On Mon, Mar 9, 2009 at 9:56 PM, chad qian <nynj.tech at hotmail.com> wrote:
> Hi,
> I need to generate random 8-digit numbers continuously.And no
> duplication among all those numbers.In other word,every single 8-digit
> number must be unique.How to do php programming?

Just to give a little different answer from what people are suggesting
you could use a sequence number and then apply a routine that just
rotates and move bits around in constant way. This will guarantee that
the number is unique without using a database (although I guess you
still need a source of the sequence number so you need to store that
somewhere).

For example, you could do something like this:

function reverse_bits($v) {
    $t = $v << 1;

    $v >>= 1;
    $v &= 0x7FFFFFFF;
    for ($i = 30; $i > 0; $i--) {
        $t |= $v & 1;
        $t <<= 1;
        $v >>= 1;
    }
    $t |= $v;

    return $t;
}

function scramble($num) {
    $num = reverse_bits($num);
    return $num ^ 0xFEEDB0A5;
}

So you feed the scramble function a sequence of numbers like 10, 11,
12, ... etc and get out a number that looks random. Of course it's not
random. It only looks random. In fact, if you feed the scrambled
number back through the scramble routine you'll get back the original
sequence number.

Mike

-- 
Michael B Allen
Java Active Directory Integration
http://www.ioplex.com/



More information about the talk mailing list