View Full Version : Quick question about "mt_rand(Start,Total);"

05-15-2008, 03:39 AM
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:

$url = array(

'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 ?


05-15-2008, 04:28 AM
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 :)