Web Analytics Made Easy -
StatCounter Generating a random number, but delete certain numbers from range. - CodingForum

Announcement

Collapse
No announcement yet.

Generating a random number, but delete certain numbers from range.

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Resolved Generating a random number, but delete certain numbers from range.

    I would like to generate a random number between 0001 and 9999 which isn't already in the database. So in the example below all numbers in the MySQL array would be eliminated from the random number function before it is called. The number it generates would then be added to the database and not be included again in the random number function.

    I don't want the random number function to just run until there is no matches because a near full database might cause an endless loop until it hits the few numbers remaining. So I would like to eliminate the current numbers in the database from the random number function FIRST, then retrieve a random number. I can't figure this one out, any ideas?

    PHP Code:
    <?php
    // Example data from MySQL database
    $mySQL = array('9876','1999','2376','4599','0012','6666','8734','2424','1010');

    foreach (
    $mySQL as $numbers) {
    $delete $numbers// Numbers to be eliminated from random number range.
    }

    $num_range range (0001,9999);

    foreach (
    $num_range as $num) {

    if (
    $num <= 999) {
    $padding "0";
    }
    if (
    $num <= 99) {
    $padding "00";
    }
    if (
    $num <= 9) {
    $padding "000";
    }
    echo 
    "\t\t$padding$num\n";
    }
    ?>


    ------
    Last edited by Len Whistler; Apr 5, 2009, 08:56 PM. Reason: Resolved
    Leonard Whistler

  • #2
    If I understood correctly, just use array_diff and array_rand to compare the 2 arrays, then get a random number of whats left.

    PHP Code:
    $used = array('9876','1999','2376','4599','0012','6666','8734','2424','1010');
    $range range (0001,9999);

    $not_used array_diff($range$used);

    $random_key array_rand($not_used1);

    echo 
    $random_key

    Comment


    • #3
      Thanks ptmuldoon. That's exactly what I want, works perfectly.




      ---------------------------
      Leonard Whistler

      Comment

      Working...
      X