SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Zealot
    Join Date
    Jun 2008
    Location
    Gloucestershire, UK
    Posts
    197
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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. #2
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    How many numbers you want to create and how many digits you want ? Is it only number or it can also be alphanumeric?
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  3. #3
    SitePoint Wizard Ren's Avatar
    Join Date
    Aug 2003
    Location
    UK
    Posts
    1,060
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I wouldn't use recursion for this.

  4. #4
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Quote Originally Posted by Ren View Post
    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.
    		}
    	}
    }

    Hope you can adjust it for your requirement!
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •