1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Multiple, unique, random numbers called by array.

Discussion in 'PHP' started by Greg-J, Apr 13, 2006.

  1. #1
    I found this in an old thread:
    $arr = array();
          while ( count($arr) < 10 ) {
              $x = mt_rand(1,10);
              if ( !in_array($x,$arr) ) { $arr[] = $x; echo "$x<br>"; }
          } 
    PHP:
    And it does exactly what I am looking for, except for I'm trying to make a change. I would like to be able to use the random numbers anywhere in the script using an array.

    The numbers would be generated and put in to an array on page load, and I could call them throughout the page using something like $randomN[2]. So $randomN[2] woudl call the 2nd (well, actually the third) number in the array. This would make $randomN[0] through $randomN[9] all unique.

    Can anyone help me with this? I'm struggling.
     
    Greg-J, Apr 13, 2006 IP
  2. TheHoff

    TheHoff Peon

    Messages:
    1,530
    Likes Received:
    130
    Best Answers:
    0
    Trophy Points:
    0
    #2
    You're most of the way there already... just had to change the array name and remove the echo.

    
    $randomN = array();
    
    while ( count($randomN) < 10 ) {
    
    	$x = mt_rand(1,10);
    
    	if ( !in_array($x,$randomN) ) { $randomN[] = $x; }
    
    } 
    
    PHP:
     
    TheHoff, Apr 13, 2006 IP
  3. Greg-J

    Greg-J I humbly return to you.

    Messages:
    1,844
    Likes Received:
    153
    Best Answers:
    0
    Trophy Points:
    135
    #3
    Ahh.. I'll give this a go in a minute. Thanks Hoff - You sexy bunch of Trans-Am driving, swim short wearing love ;)
     
    Greg-J, Apr 13, 2006 IP
    TheHoff likes this.