How to randomly pick from a list in php?

Discussion in 'PHP' started by Cyberkiller, Apr 8, 2007.

  1. #1
    Say I have something like this,

    
    if ($m == "1") {$link = "http://www.test.com;}
    header("Location: $link");
    exit();
    
    Code (markup):
    How would I change this so it would randomly pick from a list of say 50 sites?
     
    Cyberkiller, Apr 8, 2007 IP
  2. nico_swd

    nico_swd Prominent Member

    Messages:
    4,153
    Likes Received:
    344
    Best Answers:
    18
    Trophy Points:
    375
  3. RRWH

    RRWH Active Member

    Messages:
    821
    Likes Received:
    49
    Best Answers:
    0
    Trophy Points:
    70
    #3
    what you want to use is the rand() function

    Something like

    
    
    $urls = array('url1', 'url2', 'url3');
    
    $getrand =  rand(0, count($urls) -1);
    
    header("location: $urls[$getrand]");
    
    Code (markup):
    This is untested, but should do what you want
     
    RRWH, Apr 8, 2007 IP
  4. nextebizguy

    nextebizguy Peon

    Messages:
    276
    Likes Received:
    12
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Using the above, here is some working code.

    
    <?php
    $urls = array('<a href="http://www.yahoo.com">yahoo</a>', 
    '<a href="http://www.google.com">google</a>', 
    '<a href="http://www.altavista.com">altavista</a>', 
    '<a href="http://nextebizguy.com">nextebizguy</a>' );
    
    $getrand =  rand(0, count($urls) -1);
    
    echo "Random Link: $urls[$getrand]";
    ?>
    
    Code (markup):
    Put this into an html file and run it on your server.
     
    nextebizguy, Apr 8, 2007 IP