how to set a veriable to a random number?

Discussion in 'PHP' started by tyler3, Apr 20, 2008.

  1. #1
    Can anyone point me in the right direction?

    I'd have a list of numbers, and I'd like to set a single variable to pull up a random number each time it's pulled...

    So say my numbers are 1, 2, and 3..each time the script is called it will pull a random number from a list that I've made (there are only 30 or 40 numbers I want to pull from). How would I set that up in php so that when I call say $variable it pulls from that list of random numbers to use as that variable?

    Thanks!
     
    tyler3, Apr 20, 2008 IP
  2. KnuTz

    KnuTz Well-Known Member

    Messages:
    169
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    130
    Digital Goods:
    1
    #2
    use the random function ex.
    <?php
    
    $somenum = rand(1,40); 
    
    echo $somenum ; //output random number  from 1 to 40
    ?>
    PHP:
     
    KnuTz, Apr 20, 2008 IP
  3. CPURules

    CPURules Peon

    Messages:
    67
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    If you're numbers are sequential, then the above will work. If they aren't:

    Assuming you're using the number 2, 3, 5, 7, 11, 13, and 17 (primes):
    
    <?php
    $numbers = array(1 => 2, 2 => 3, 3 => 5, 4 => 7, 5 => 11, 6 => 13, 7 => 17);
    $r = rand(1, 7);
    $random = $numbers[$r];
    echo $random;
    ?>
    
    PHP:
    The above will also work with random words(just replace the numbers after the "=>" with a word enclosed by quotes)
     
    CPURules, Apr 20, 2008 IP
  4. qurve

    qurve Peon

    Messages:
    30
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Even easier:

    
    $numbers = array(1,2,4,8,16,32,64);
    $number = array_rand($numbers);
    echo $number;
    
    PHP:
     
    qurve, Apr 21, 2008 IP
  5. tyler3

    tyler3 Peon

    Messages:
    270
    Likes Received:
    4
    Best Answers:
    0
    Trophy Points:
    0
    #5
    amazing. Thanks for the help!!
     
    tyler3, Apr 22, 2008 IP