Make a PHP variable random and add it to an input value

Discussion in 'PHP' started by blueparukia, Aug 25, 2007.

  1. #1
    Say I have a file named "value.php" . I want it to choose a random value for a variable.

    <?php
    $siteaddress = random
    ?>
    PHP:

    Obviously I want to replace "random" with a few web addresses, and select one as random.
    I then want to make it into an input box in my index page

    <input type="text" value="php variable" />
    Code (markup):
    So how would I make the variable set to a random address and then apply it to the input?



    Thanks,

    BP
     
    blueparukia, Aug 25, 2007 IP
  2. tandac

    tandac Active Member

    Messages:
    337
    Likes Received:
    11
    Best Answers:
    0
    Trophy Points:
    58
    #2
    If I understand you correctly:
    
    $sites=Array("www.google.ca","www.yahoo.ca","www.cnn.com");
    $pick=$sites[mt_rand(0,count($sites)-1)];
    
    PHP:
    Followed up with:
    
    <input type="text" name="txtSomething" value="<?php echo $pick; ?>" />
    
    HTML:
     
    tandac, Aug 26, 2007 IP
  3. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #3
    Yeah, basically that is correct. But I want to apply it to several different documents, so I will need to save the variable into a different PHP file, and include it into the form somehow.



    Thanks a lot,

    BP
     
    blueparukia, Aug 26, 2007 IP
  4. ssanders82

    ssanders82 Peon

    Messages:
    77
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Put tandac's code in a common.php file in a function called GetRandomSite (make sure to type "return $pick" as the last line of the function).

    Then include that file in all your pages. When you need a random site, just type echo GetRandomSite()
     
    ssanders82, Aug 27, 2007 IP
  5. blueparukia

    blueparukia Well-Known Member

    Messages:
    1,564
    Likes Received:
    71
    Best Answers:
    7
    Trophy Points:
    160
    #5
    Awesome, thanks :)
     
    blueparukia, Aug 27, 2007 IP