Can someone please give me the quick snippet of code that I need to display random links? I just want to enter about 25 links, and have it randomly pick 3 each time.
This should work : $rand = rand(1,3); switch ($rand) { case 1: echo "<a href='http://www.link1.com'>link1</a>"; break; case 2: echo "<a href='http://www.link2.com'>link2</a>"; break; case 3: echo "<a href='http://www.link2.com'>link2</a>"; break; } PHP:
My preference would be to store the links in an array and then use count to automatically get the top number for the top number in the rand function. $links = array(0 => "<a href='http://www.link0.com'>link0</a>", 1 => "<a href='http://www.link1.com'>link1</a>", 2 => "<a href='http://www.link2.com'>link2</a>"); $rand_num = rand(0, (count($links) - 1)); echo $links[$rand_num]; PHP: This way there is less to do if you want to add new links and it is really easy to put all the links in a separate file if you wish.
$links = array ( "<a href=\"http://google.com\">Google</a>", "<a href=\"http://msn.com\">MSN</a>", "<a href=\"http://porn.com\">Porn</a>", "<a href=\"http://space.com\">Space</a>", "<a href=\"http://more.com\">More</a>", "<a href=\"http://less.com\">Less</a>" ); function rand_links( $links, $num, $glue = "<br />" ) { if(!is_array( $links ) ) return false; foreach( array_rand( $links, $num ) as $selected ) $return .= $links[ $selected ] . $glue; return trim( substr( $return, 0, strlen( $return ) - strlen( $glue ) ) ); } echo rand_links( $links, 3 ); echo "<br /><br /><hr />"; echo rand_links( $links, 3, " | " ); PHP:
I haven't come across the array_rand function before. It certainly simplifies things. The whole variable number thing, which I seem to have skipped, also addresses the question in full.