...

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



mypointofview
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:


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

Fou-Lu
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 :)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum