# Thread: Recursive Method To Create Unique Random Number

1. ## Recursive Method To Create Unique Random Number

Hello,

I've got to make a unique random number as part of a program, I was thinking that a recursive method might be up to the job but seeing as I've not messed with recursion I was hoping for advice.

This is what I've got:

PHP Code:
```     protected \$items = array();     public function create_ref() {                  \$ref_id = rand();                  if (in_array(\$ref_id, \$this->items)) {             \$this->create_ref();         }else{             return \$ref_id;         }              }  ```
It seems to work, but I was hoping that someone might have done this kind of thing before and either reassure me that I'm not creating a bug or point me in the right direction.

Thanks,

Jon

2. How many numbers you want to create and how many digits you want ? Is it only number or it can also be alphanumeric?

3. I wouldn't use recursion for this.

4. Originally Posted by Ren
I wouldn't use recursion for this.
Me too! I think something like below is enough but you have to be clear about how many numbers you want to create:
Code PHP:
```protected \$items = array();
public function create_ref(\$number = 10) {
for(\$i = 0; \$i < \$number; \$i++){
\$ref_id = rand();
// check if the same number already in the array or not.
if (!in_array(\$ref_id, \$this->items)) {
\$this->items[] = \$ref_id; // add in the array.
}
}
}```