0

I have an event with 10 spaces available for booking. When a user registers for the event, I need to assign them a random draw number from 1 through 10. I will include this number in the confirmation email they receive after registration.

I know I can generate the number like this:

$num = random_int(1, 10); 

But I can't figure out how to ensure that the number assignment is unique. I can't give someone a number that has already been assigned to another registrant. People will not register at the same time, so I somehow need the function to check against all the previously assigned numbers before assigning a random number from the remaining numbers.

If it matters, event registrants will only be logged-in users, so I could assign something to their user meta if needed.

How would you go about this? Thank you!

2
  • it looks like you find the answer yourself : "assign something to their user meta"
    – mmm
    Commented Jul 26 at 2:20
  • I still need to figure out how to remove previously assigned numbers from the 1-10 and then have it assign a random number from the unused numbers.
    – LBF
    Commented Jul 26 at 3:12

1 Answer 1

0

All right, I figured it out. But if someone wants to suggest something better, please feel free and I will mark it correct.

// array of previously-assigned numbers (get this by looping through the registered users -not shown)
$numbers_already_taken = array(3,8,1);

// get all the numbers between 1-10
$numbers = range(1, 10);

// shuffle the numbers so they are in random order
shuffle($numbers);

// set up variable to hold this user's draw #
$draw = '';
    
// loop through the available numbers
foreach ($numbers as $number) {
    
    // ignore numbers that have already been assigned
    if (!in_array($number, $numbers_already_taken)) {

      // assign the first matching draw number (break stops it)
      $draw = $number;
      break;

    }
   
}

echo 'Your Draw Number: ' . $draw;

// save $draw to the user's profile or booking (not shown)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.