Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    mypointofview
    Guest

    Quick question about "mt_rand(Start,Total);"

    I want to echo a random URL on a page. My question is: do I use "0" as Start (not "1") and as Total I'd use the total amount of URLs but minus 1 ?

    If yes, then the following array of 9 URLs should work, writing "$random = mt_rand(0,8);" ?

    Here's my full code:

    PHP Code:
    <?php
    $url 
    = array(

    'http://www.link-1.com',
    'http://www.link-2.com',
    'http://www.link-3.com',
    'http://www.link-4.com',
    'http://www.link-5.com',
    'http://www.link-6.com',
    'http://www.link-7.com',
    'http://www.link-8.com',
    'http://www.link-9.com'  // last item without comma!

    );
    $random mt_rand(0,8);  // second digit must be one less than the total amount of all links in list above.
    $link $url[$random];

    echo 
    $link;

    ?>
    I just want to make sure, asking somebody more experienced than me, because on the Web sometimes there's other snippets floating around, starting with 1 and as total they use the real total amount -- which I think is wrong and would never make the first item in the list to show up ever... Correct ?

    Thanks.
    Last edited by mypointofview; 05-15-2008 at 02:48 AM.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    I'd do it your way mate.
    Some languages have different array handling (I'm thinking VB is 1 based, but someone would need to confirm). PHP is 0 based arrays, as in they start at zero. mt_rand is an inclusive function, so it will randomly generate a number between the first (0), and last (8), including the first and the last as options. The other option is to do the 1 and 9, but then you need to subtract one from result value. This takes one cpu cycle that you can avoid by just doing the 0, 8. Go optimization
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 


  •  

    Posting Permissions

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