Hi,

Can anyone help me by writing a little php scripts.

When a page gets hit I want to display a 8 digit random number. The main point is that number must be UNIQUE. If the page gets hits 100 times, no two numbers among 100 should be same.

Thanks in advance.

    Well, random and unique do not mix very well together. A few options:

    1. Create a database table to store the numbers that have been used, defining the number field as unique. When a number is needed, generate a random number with [man]rand/man or [man]mt_rand/man, then attempt to insert it into that database table. If you get an error that it's a duplicate value, try again until you get an unused value, then proceed. The obvious drawback is that as more and more numbers get used, the more you are likely to run into duplicates, possibly causing multiple database calls and slowing your script.

    2. Populate a database table with a series of unique values. When you need a number, you do a query to get one row with a random sort, then either delete that row from the table or mark it as "used" (thus the initial query would have a where clause limiting the result to rows not so marked). To avoid race conditions that might cause duplicates, you would need to implement a read/write lock on the table before grabbing a number.

    3. If you don't mind some letters thrown in with the numbers, you could use the current timestamp value in hexadecimal to get an 8-character value:

      $random = dechex(time());
      

      The one problem with this would be if two users requested numbers within the same clock second.

      There are two problems with your question:

      1. If the number is random it may be repeated; if it could not be repeated it is no longer random. But I get what you mean, I just wanted to point it out.

      2. Normally people help others help themselfes here, they don't develop things for them. You are asking someone else to do exactly that without showing what you have tried.

        If the number is random it may be repeated; if it could not be repeated it is no longer random.

        That is not true: it is akin to selection at random without replacement.

          You really got me thinking about this laserlight. I have to admit that you are right. Or that if you really want it to be random you can't have any constraints, even not smallest or highest number allowed. But that would be impossible to accomplish.

          I stand corrected.

            Write a Reply...