Jump to content

Random link from original link


jokerfool

Recommended Posts

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

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>";
?>

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

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.