jokerfool Posted August 22, 2009 Share Posted August 22, 2009 On my page I have a series of links already placed, one link though I would like to be a random link so each time the page is loaded the link changes. The current code for the link is: <li><a href="index.php" title="Mystery Link">Mystery Link</a></li> How can I add a piece of code so that specific link changes each time the page loads? I had a thought if I had a file that contained random website links and the code grabbed one of the links and each time the page was loaded the link would send the user to a different site. How can I go about doing this? Can someone show me an example please? Thank you. Link to comment https://forums.phpfreaks.com/topic/171421-random-link-from-original-link/ Share on other sites More sharing options...
thebadbad Posted August 22, 2009 Share Posted August 22, 2009 You can specify an array of links, and then pick a random one with array_rand(): <?php $links = array( 'First link' => 'http://example.com/1', 'Second link' => 'http://example.com/2', 'Third link' => 'http://example.com/3' ); $rand_key = array_rand($links); echo "<a href=\"{$links[$rand_key]}\" title=\"{$rand_key}\">{$rand_key}</a>"; ?> Link to comment https://forums.phpfreaks.com/topic/171421-random-link-from-original-link/#findComment-904031 Share on other sites More sharing options...
AngelicS Posted August 22, 2009 Share Posted August 22, 2009 You can use the following code: <?php //This varaible contains a random number between 1 and 3 $rand=rand(1,3); //The switch statement will check wich number the rand variable contains. //Depending on the $rand variable value, The variable $link, and $name will get a value. //Then you use these values in the link on the bottom. switch($rand) { case 1: $link='http://www.google.com'; $name='Google'; break; case 2: $link='http://www.phpfreaks.com'; $name='PHP Freaks'; break; case 3: $link='index.php'; $name='Homepage'; break; default: echo "something went wrong"; break; } ?> <a href="<?php echo $link; ?>"><?php echo $name; ?></a> If you don't know how to use the switch statement, check the following links: PHP Manual - Switch http://us2.php.net/manual/en/control-structures.switch.php W3Schools - Switch http://www.w3schools.com/PHP/php_switch.asp Best Wishes //AngelicS Link to comment https://forums.phpfreaks.com/topic/171421-random-link-from-original-link/#findComment-904034 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.